I have found myself unable to explain why the following piece of code works. Needless to say, I am quite new to C++…
#include <cstdio>
void foo(char* p)
{
p[0] = 'y';
}
int main()
{
char a[1];
a[0] = 'x';
printf("a[0] = %c\n", a[0]);
foo(a);
printf("a[0] = %c\n", a[0]);
return 0;
}
This program outputs
a[0] = x
a[0] = y
What intrigues me us that I am not passing a pointer, but an array, to foo. So how can foo change the value of the array a? Does this apply only to arrays of char?
The answer to Difference between char and char[1], confirms my observation, but it does not go into detail about why this is the case.
Thanks!
In C, arrays, in most contexts (*), decay into a pointer to their first element.
In your case, the array
adecays into a pointer toa[0].The array
int arr[12][23], when used just by its identifier, decays to a pointer to its first element, namelyarr[0], which is of typeint (*)[23](pointer to array of 23 ints).(*) Arrays do not decay when used as the argument to the
sizeofoperator, or when used as argument to the&operator or when used as initializer (a string literal) for a character array.