Home > Software engineering >  array name and pointer name confusion
array name and pointer name confusion

Time:12-28

In C language, an Array is a collection of same data type, that is when we are defining an array like this :

int my_list[50];

we are allocating 50 consecutive location in the computer memory to store 50 integer.

when somebody says my array is "my_list", what does it mean? does it collectively denotes all the 50 spaces that I have defined in the memory?

if that is the case , when I'm trying to learn pointers, they say, no no, there is a pointer whose name is "my_list" and it points to my_list[0];

my conclusions are like this: "my_list" does denote all the 50 memory location collectively, but when we are defining the array , the machine is generating a pointer whose name is "accidentally" "my_list" and it points to my_list[0];

array my_list denotes all the 50 location collectively and pointer my_list only points to my_list[0], though their name overlaps they are totally different things.

please correct me if i'm wrong.

CodePudding user response:

does it collectively denotes all the 50 spaces that I have defined in the memory?

Yes, my_list is the array.

… they say, no no, there is a pointer whose name is "my_list" and it points to my_list[0];

“They” are wrong. There is no pointer named my_list.

However, when an array is used in an expression, it is automatically converted to a pointer to its first element except when it is the operand of sizeof, is the operand of unary &, or is a string literal used to initialize an array.

Thus, if you, for example, use my_list like a pointer, as in int *p = my_list 5;, or you pass it to a function, as in foo(50, my_list);, then it is automatically converted to a pointer, as if you had written int *p = &my_list[0] 5; or foo(50, &my_list[0]);.

For the exceptions: With sizeof, sizeof my_list gives the size of the whole array, the size of 50 int. There is no automatic conversion to a pointer, so sizeof my_list does not give the size of a pointer. And with unary &, &my_list is a pointer with type “pointer to array of 50 int” rather than a pointer with type “pointer to pointer to int”.

(An array you declare with a name, like my_list, is of course not a string literal. A string literal can be used to initialize an array, as in char MyString[] = "Hello";. In this case, the array formed by the string literal is used to initialize buffer; it is not converted to a pointer.)

  •  Tags:  
  • c
  • Related