Search code examples
cpointersstructstructuredeclaration

How can I declare a Pointer to a struct in C?


I have learned that pointers can be declared in 3 different ways:

int* a;
int *b;
int * c;

I prefer:

int* a;

While declaring a pointer to a structure, is it correct to write it like following:

struct Card {
   int a;
};
struct Card my_card = { 3, 7 };
struct Card* p = &my_card; 
(*p).a = 8; 

I am confused because everywhere I have found it is declared as following:

struct Card *p = &my_card;

Thanks in advance.


Solution

  • It doesn't matter where you put the spaces. struct Card* p and struct Card *p are equally valid; it's just a matter of style as to which one you prefer.

    I agree the second form is more common, but what's most important is that you use one form consistently throughout your code. Your boss / teacher / other developers may also have coding style standards that specify which form to use.