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

What is the difference between the next pointer initialization?

char array_thing[10]; char *char_pointer; 

What is the difference in the next initialization?

 1.) char_pointer = array_thing; 2.) char_pointer = &array_thing 

Is the second initialization valid?

+6
source share
4 answers

The second initialization is invalid. 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 are looking for a pointer to the first element of the array.

+5
source

See comp.lang.c FAQ, Question 6.12: http://c-faq.com/aryptr/aryvsadr.html

+1
source

Please note that there are no initializations in the code you submitted. However, you should keep in mind that arrays break up into pointers (pointer to the first element inside the array). Accepting the address of the array is, of course, permissible, but now you use (*char)[10] instead of char* .

0
source

In the first case, you set char_pointer to the first element of array_thing (rather, its address). Using pointer arithmetic will lead you to other elements, as well as indexing. for instance

 char_pointer[3] = 'c'; 

coincides with

char_pointer + = 3; char_pointer = 'c';

The second example ... I do not believe that this is the way you do it.

0
source

Source: https://habr.com/ru/post/898101/


All Articles