简体   繁体   中英

Typedef struct pointers

I want to pass a pointer to my struct into a function to edit the struct.

This does not work:

typedef struct{

  unsigned char x;
  unsigned char y;
  float z;


}C_TypeDef;


C_TypeDef *ptr_struct;  //This is the part that I change to get it to work.


void print_TypeDef(C_TypeDef *report, unsigned char x_data)
{

   report->x = x_data;
   printf("x is equal to %d", report->x);


}

int main(void)
{

    print_TypeDef(ptr_struct,0x23);
    getchar();

}

Now if I change the part that I declare the pointer to this is still does not work. This does not work:

C_TypeDef x_struct;
C_TypeDef *ptr_struct;
ptr_struct = &x_struct;

But if I change it to this, it does work!!

C_TypeDef x_struct;
C_TypeDef *ptr_struct = &x_struct;

My question is why don't the first two work? This is bugging me.

The problem of the first version is, you didn't allocate memory for what ptr_struct points to, it usually leads to segmentation fault. This is fixed in:

C_TypeDef x_struct;
C_TypeDef *ptr_struct = &x_struct;

That's why the third version works. Then what's wrong with the second version? Because you can't assign a global variable outside any functions, you can initialize them like what you did in the third version, or you should assign it in some function, like in main :

C_TypeDef x_struct;
C_TypeDef *ptr_struct;

//omit other parts

int main(void)
{
    ptr_struct = &x_struct;  //Here assign the pointer a value
    print_TypeDef(ptr_struct,0x23);
    getchar();
}

The first version of code is not working because you have created a pointer type to the structure, and not really assigned any address. But trying to access it in the calling function

print_TypeDef(ptr_struct,0x23);\\here ptr_struct is not pointing to any instance of the                     structure.

The second version is not working because the statements

C_TypeDef x_struct;
C_TypeDef *ptr_struct;

is perfectly correct, but the next statement of assigning a value to an variable is not at all possible outside of any function.

C_TypeDef x_struct;\\correct, creating a instance of struct type
C_TypeDef *ptr_struct;\\correct, creating a pointer to an structure 
ptr_struct = &x_struct;\\wrong, as this statement is possible only inside a function.

Incidentally for your code to work you need not create both the structure instance and a pointer of that instance, instead it will work well by

C_TypeDef x_struct;

and in main, call the function like this,

int main(void)
{

    print_TypeDef(&x_struct,0x23);
    getchar();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM