gcc 4.4.4
What am I doing wrong?
char x[10];
char y[] = \"Hello\";
while(y != NULL)
*x++ = *y++;
Many thanks for any advice.
Most likely you fell victim to a popular misconception that "array is a pointer", i.e. when you define an array what you actually get is an ordinary pointer that points to some block of memory allocated somewhere. In your code you are making an attempt to increment that pointer.
The code does not "work" because in reality arrays are not pointers. Arrays are arrays. Arrays cannot be incremented. There's no such operation as "increment an array" in C language. In fact, arrays by themselves in C are non-modifiable lvalues. There are no operations in C that can modify the array itself (only individual elements can be modifiable).
If you want to traverse your arrays using the "sliding pointer" technique (which is what you are actually trying to do), you need to create the pointers explicitly and make them point to the starting elements of your arrays
char *px = x;
char *py = y;
After that you can increment these pointers as much as you want.
Since you've defined both x
and y
as arrays, you can't modify them. One possibility would be to use pointers instead:
char x[10];
char *xx = x;
char *y = "Hello";
while (*y != '\0')
*xx++ = *y++;
Note that I've also fixed your termination condition -- a pointer won't become NULL
just because it's reached the end of a string.
char x[10];
char y[] = "Hello";
char *p_x = &x[0];
char *p_y = &y[0];
while(*p_y != '\0') *p_x++ = *p_y++;
Since you can't modify the array addresses (done by x++
and y++
in your code) and you can modify the pointer address, I copied over the address of the array into separate pointers and then incremented them.
If you want, I'm sure you can reduce the notation, but I hope you got the point.
Arrays in C are indeed pointers, but constant pointers, which means after declaration their values can't be changed.
int arr[] = {1, 2, 3};
// arr is declared as const pointer.
(arr + 1)
is possible but arr++
is not possible because arr
can not store another address since it is constant.
We can not modify a array name, but What about argv++
in f(int argv[])
?
Quotes from K&R in p99 “an array name is not a varible; construction like a = pa
and a++
are illegal" which says the name of an array is a synonym for the location of the initial element.”
But why in function parameter func(char *argv[])
, we can do argv++
despite of argv
is a array name.
And in int *a[10]
, we can't do the a++
like argv++
.
The name of array is a synonym for the location of the initial element. ---K&R
arrayname++
is illegal.
In function parameter, such as char *argv[]
, it is the same as char **argv
. type *arrayname_para[]
in parameter is a another synonym for type **arrayname_para
.
Arrays are constant pointers. We can't change them.
int q;
int *const p = &q;
p = NULL; // this is not allowed.