-3

I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct vector_{
    int x;
    double y;
    double z;
} *vector;

void modi(vector a);

int main() {
  vector var;
  var->x = 2;
  modi(var);
  return 0;
}

void modi(vector a){
  printf("avant modif %d",a->x);
  a->x = 5;
  printf("avant modif %d",a->x);
}

I tried to run it but I got a segmentation fault.

The problem is simple: the access/modify with a struct pointer variable.

I look on Stack Overflow but I got an incomplete answer for my problem: https://stackoverflow.com/a/1544134

What is the right way to access/modify in this case (a struct pointer variable)?

Community
  • 1
  • 1
hp95
  • 25
  • 1
  • 10
  • 1
    `vector var = malloc(sizeof(vector));` You must allocate space if you're going to do it this way... – Kevin Nov 11 '15 at 00:50
  • 1
    Maybe if you didn't try to hide indirection behind your typedef you wouldn't confuse yourself? – EOF Nov 11 '15 at 00:51
  • 2
    @Kevin `vector var = malloc(sizeof(*var));` – BLUEPIXY Nov 11 '15 at 00:51
  • 1
    You never allocated any space for the pointer to point at; you invoke undefined behaviour when you dereference the uninitialized pointer. And, in general, don't hide pointers behind typedefs. – Jonathan Leffler Nov 11 '15 at 00:52
  • @EOF I see that hide indirection was more securized than the standard way. It was the reason I will use it. – hp95 Nov 11 '15 at 00:54
  • See [Is it a good idea to typedef pointers?](http://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) for the low-down. There are circumstances when it is OK to do so — pointers to functions and (possibly) pointers to opaque types are examples. However, if you need to dereference the data in the type, it is best to avoid typedefing the pointer. – Jonathan Leffler Nov 11 '15 at 01:03

1 Answers1

1

Please try this, it works, I expanded a bit. Please read the comments in the code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct vector_
{
  int x;
  double y;
  double z;
};

typedef struct vector_ *vector;
void modi( vector a );

int main(  )
{
  struct vector_ av;    // we have a structure av
  vector var = &av;     // pointer var points to av
  var->x = 2;

  printf( "\ndans main() avant call to modi() %d", var->x );

  modi( var );

  printf( "\ndans main() apres call to modi() %d", var->x );
  return 0;
}

void modi( vector a )
{
  printf( "\ndans modi() avant modif %d", a->x );
  a->x = 5;
  printf( "\ndans modi() apres modif %d", a->x );
}
BobRun
  • 756
  • 5
  • 12