tags:

views:

134

answers:

5

Hello,

gcc 4.4.4

Maybe I am being dumb. But what am I doing wrong?

 char x[10];
 char y[] = "Hello";
 while(y != NULL)
     *x++ = *y++;

Many thanks for any advice,

+3  A: 
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.

Jacob
+3  A: 

x++ is the short form of x = x + 1. However, x here is an array and you cannot modify the address of an array. So is the case with your variable y too. What you can do is defined two pointers pointing to the two arrays and increment those pointers or do the following.

 char x[10];
 char y[] = "Hello";
 int i=0;
 while(y[i] != 0)
 {
     *(x+i) = *(y+i);
     i++;
 }
 x[i] = 0;
naivnomore
Why would you mix the `*(x+i)` and `x[i]` forms in the same code?
caf
+2  A: 

x and y are arrays, not pointers.

They decay into pointers in most expression contexts, such as your increment expression, but they decay into rvalues, not lvalues and you can only apply increment operators to lvalues.

Charles Bailey
+1  A: 

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.

Jerry Coffin
I guess a nul is better than a null.
robUK
+3  A: 

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.

AndreyT