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?
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
The name
originon the RHS “decays” to be of typeLine *, and points to the first element oforiginarray, whereasresponseis 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,
doesn’t copy all the memory in
origintoresponse. As I mentioned above, and in more detail in the link above,originpoints to the first element of theoriginarray in this context, so*originis actually the first element of the array. Therefore,*response=*origin;just copies the value of the first element of theoriginarray to the first element ofresponse. Since you haven’t assigned a value toresponse[1], it contains garbage.If you want to copy the array data over, you can do a loop:
Or, you can use
memcpy():(The above is for C, Objective-C may have differences and other ways of doing what you want to do.)