i'm new to programming world, am interested in iphone dev.
right now i'm reading Stephen Kochan's book "Programming in Objective-C 2.0".
and had some problems i couldn't figured out on my own.
I posted the following question on the official forum for the book, but it seemed like no one's there. I googled this site.
"I was reading pointers on chapter13 today, and had a question.
since a array name without a subscript is a pointer to the beginning of the array,
why can't we use increment on the array name like ++array,
and when you assign it to a pointer variable, you can do that with pointer?
for example, we have a character array
char array[] = {'a','b','c','\0'}
and you cannot do this:
NSLog(@"%c", *(++array));
although this works fine:
NSLog(@"%c", *(array+1));
then you assign it to a pointer:
char *ptr = array;
then it works:
NSLog(@"%c", *(++ptr));
You can't consider arrays as pointers. Although arrays are mentioned sometimes as a pointer to the beginning of the array, there are differences between both of them.
One of the differences at your case is that arrays address cannot be changed, so when you try to increment the array then you are trying to manipulate the address which isn't allowed. However, in the second case you take the initial address and incremented it by one which didn't do any changes to the array address.
When you define a pointer and assigns its value to the beginning of the array, then you are dealing with the pointer (third case). So incrementing it and decrementing it will not affect the address of the array.
Hope that helps.
Quote:
Originally Posted by bamboo
i'm new to programming world, am interested in iphone dev.
right now i'm reading Stephen Kochan's book "Programming in Objective-C 2.0".
and had some problems i couldn't figured out on my own.
I posted the following question on the official forum for the book, but it seemed like no one's there. I googled this site.
"I was reading pointers on chapter13 today, and had a question.
since a array name without a subscript is a pointer to the beginning of the array,
why can't we use increment on the array name like ++array,
and when you assign it to a pointer variable, you can do that with pointer?
for example, we have a character array
char array[] = {'a','b','c','\0'}
and you cannot do this:
NSLog(@"%c", *(++array));
although this works fine:
NSLog(@"%c", *(array+1));
then you assign it to a pointer:
char *ptr = array;
then it works:
NSLog(@"%c", *(++ptr));