简体   繁体   中英

C pointers: what's the difference between struc* A, struct *A and struct * A?

I'm doing some researches to better understand pointers in C, but I'm having a hard time understanding these: Is 'struct* A' a pointer on a structure? Then what is 'struct *A'? And I've seen someone writing 'int const * a', what does this mean?

what's the difference between struc* A , struct *A and struct * A ?

They're equivalent(ly wrong). C is a free-form language, whitespace doesn't matter.

Is struct* A a pointer on a structure?

No, it's (still) a syntax error ( struct is a reserved keyword). If you substitute a valid structure name in there, then it will be one, yes.

int const * a , what does this mean?

This declares a to be a pointer to const int .

struct *A , struct* A and struct * A are all the same thing and all eqaully wrong since you're missing the struct's name.

int const *a is a the same as const int *a and it means pointer to a const integer.

Aside: int * const a is different and it means const pointer and a non const integer.

They are all identical.

struct *A = struct* A = struct*A = struct * A .

As others have already mentioned, struct * A et cetera are incorrect but identical.

However, a structure and a pointer can be created in the following manner:

/* Structure definition. */
struct Date
{
    int month;
    int day;
    int year;
};

/* Declaring the structure of type Date named today. */
struct Date today;

/* Declaring a pointer to a Date structure (named procrastinate). */
struct Date * procrastinate;

/* The pointer 'procrastinate' now points to the structure 'today' */
procrastinate = &today;

Also, for your secondary question about the different ways in which pointers are declared, "What is int const * a ?", here is an example that I adapted from Programming in C, by Stephen G. Kochan :

char my_char = 'X';

/* This pointer will always point to my_char. */
char * const constant_pointer_to_char = &my_char;
/* This pointer will never change the value of my_char.   */  
const char * pointer_to_a_constant_char = &my_char;
/* This pointer will always point to my_char and never change its value. */
const char * const constant_ptr_to_constant_char = &my_char; 

When I first got started, I would find it helpful to read the definition from right to left, substituting the word 'read-only' for 'const'. For example, in the last pointer I would simply say, "constant_ptr_to_constant_char is a read-only pointer to a char that is read-only". In your question above for int const * a you can say, "'a' is a pointer to a read-only int". Seems dumb, but it works.

There are some variations but when you run into them, you can find more examples by searching around this site. Hope that helps!

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