views:

201

answers:

1

I just made my first steps moving into Objective-C. I have a very simple question about how arrays works.

I have two .m files:

1)

Line = origin[6];
forloop(i...i++) {
    origin[i]=7;
}
[buildSubview:origin];

2)

Line response[6]; 

-(id)buildSubview:(Line[])origin {
    *response=*origin;
    NSLog(@"response[1]=%o",response[1]);
    NSLog(@"origin[1]=%o",origin[1]);
    ........
    .....
}

The output I get is:

response[1]=0; <-- I would expect the same value as origin
origin[1]=7;

But if I ask to print the value at index 0 I get what I expected:

response[0]=7; <-- Now they are the same
origin[0]=7;

I am asking why two different values ? And also, why if I write

response=origin;

I get an incompatible assignment compile error?

+3  A: 

Briefly, sometimes, the name of an array in C "decays" to a pointer to the first element of the array, and that is causing you trouble.

When you write

response=origin;

The name origin on the RHS "decays" to be of type Line *, and points to the first element of origin array, whereas response is of type "array [6] of Line". Since the two types are not compatible (it doesn't make sense to initialize an array with a pointer), it is an error.

Now,

*response=*origin;

doesn't copy all the memory in origin to response. As I mentioned above, and in more detail in the link above, origin points to the first element of the origin array in this context, so *origin is actually the first element of the array. Therefore, *response=*origin; just copies the value of the first element of the origin array to the first element of response. Since you haven't assigned a value to response[1], it contains garbage.

If you want to copy the array data over, you can do a loop:

size_t i;
for (i=0; i < 6; ++i)
    response[i] = origin[i];

Or, you can use memcpy():

memcpy(response, origin, sizeof response);

(The above is for C, Objective-C may have differences and other ways of doing what you want to do.)

Alok
@Peter, thanks for the spelling fix.
Alok
thanks for this clear explanation, I just voted it. In java as in some other object oriented language, you may well know that when I write objectx=objecty I got two references to the same object. I was trying to achieve that with objective-c, with a preferred way of learning how to do in a non object oriented language like C.
Leonardo
s/memset/memcpy
Paul Hankin
@Paul: Thanks! Time to 'set' myself in the bed now.
Alok