简体   繁体   中英

What is the correct way to initialize a pointer in c?

What is the difference between the following initialization of a pointer?

char array_thing[10];

char *char_pointer;

what is the difference of the following initialization?

1.) char_pointer = array_thing;

2.) char_pointer = &array_thing

Is the second initialization even valid?

The second initialization is not valid. You need to use:

char_pointer = array_thing;

or

char_pointer = &array_thing[0];

&array_thing is a pointer to an array (in this case, type char (*)[10] , and you're looking for a pointer to the first element of the array.

请参阅comp.lang.c常见问题,问题6.12: http//c-faq.com/aryptr/aryvsadr.html

Note that there are no initializations at all in the code you posted. That said, you should keep in mind that arrays decay to pointers (a pointer to the first element within the array). Taking the address of an array is certainly valid, but now you have a (*char)[10] instead of a char* .

In the first case, you're setting char_pointer to the first element of array_thing (the address of it, rather). Using pointer arithmetic will bring you to other elements, as will indexing. For example

char_pointer[3] = 'c';

is the same as

char_pointer += 3; char_pointer = 'c';

The second example...I don't believe that's valid the way you're doing it.

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