Arrays are arrays and pointers are pointers, but the name of the array works like a pointer to it's first element. Why did I say works like ? One of the reasons is exactly this:
- sizeof pointer => is 8 bytes on 64bit sys
- sizeof array => is the capacity of the array * size in bytes of the type of the elements the array is composed of. (so
int array[5]; sizeof array;
should return 20 bytes and char array[5]; sizeof array;
should return 5 bytes)
People that implemented C just decided that it should be this way.
But when you pass an array into a function, the same people that implemented C decided that the array should decay to a pointer.
So in main(), the name a
is an array. Inside the function, the name a
has decayed to a pointer.
Maybe this helps:
2.2: But I heard that char a[] was identical to char *a.
Not at all. (What you heard has to do with formal parameters to
functions; see question 2.4.) Arrays are not pointers. The array
declaration "char a[6];" requests that space for six characters be set
aside, to be known by the name "a." That is, there is a location
named "a" at which six characters can sit. The pointer declaration
"char *p;" on the other hand, requests a place which holds a pointer.
The pointer is to be known by the name "p," and can point to any char
(or contiguous array of chars) anywhere.
As usual, a picture is worth a thousand words. The statements
char a[] = "hello";
char *p = "world";
would result in data structures which could be represented like this:
+---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
+-----+ +---+---+---+---+---+---+
p: | *======> | w | o | r | l | d |\0 |
+-----+ +---+---+---+---+---+---+
It is important to realize that a reference like x[3] generates different code depending on
whether x is an array or a pointer. Given the declarations above, when
the compiler sees the expression a[3], it emits code to start at the
location "a," move three past it, and fetch the character there. When
it sees the expression p[3], it emits code to start at the location
"p," fetch the pointer value there, add three to the pointer, and
finally fetch the character pointed to. In the example above, both
a[3] and p[3] happen to be the character 'l', but the compiler gets
there differently. (See also questions 17.19 and 17.20.)
https://www.lysator.liu.se/c/c-faq/c-2.html#2-2
If this answers your question, please click the check mark to accept.