explanation needed :)

I have come across a few codes that i do not really understand and I would be happy if somebody would go through the codes so I could understand it better :)

In this code, I have to determine what would be printed on the console window:

char n[] = {'a', 'b', 'c'};
char* m = n;
cout << n[0] << " " << *m << endl; output?
m++;
cout << n[0] << " " << *m << endl; output?
n[2]++;
cout << n[2] << " " << *m << endl; output?
*m = '0';
cout << n[1] << " " << *m << endl; output

Could somebody explain it to me please? Every bit of help is appreciated :)
Kevin84,

I will give it a try, anybody let me know if I get something wrong.

Line 1. creates an array of unknown size and initializing it to the three elements of a, b, c.

Line 2. creates a char pointer m and sets it's address to the first element of array n.

Line 3. prints the first element of the array n and dereferencing the pointer prints the value at the address of m.

Line 4. adds 1 to m but, since m is a pointer it move the pointer the size of a char to the next element in the array. Pointer arithmetic depends on the type of pointer char, short, int, float or double. Since each is a different size of bytes adding one or two has a different meaning.

line 5. prints n[0] which is "a" and dereferencing m prints the value of "b" which m now points to.

Line 6. n[2] holds the ascii value for "c"". The ++ adds one to the asci value of “c” changing it to the asci value of “d”.

Line 7. n[2] now prints the new value of “d” (changed I line 6) and m still point to the second position of the array which is “b” or the same as n[1].

Line 8. dereferences the pointer to get to the value which is set to zero.

Line 9. prints [code]n[1][code] which is now zero and not “b”. m is still pointing to the second element (as changed in line 4). So, the last output is 0 0.

If I have state anything wrong somebody let me know please,

Hope this helps,

Andy
I think this type of explanations are somehow better than dry definitions and simple examples in tutorials and guides.
Thank you for that.
char n[] = {'a', 'b', 'c'};
Line 1. creates an array of unknown size and initializing it to the three elements of a, b, c.

The array will have a known size of 3, since 3 elements are provided.

char* m = n; m is now a pointer alias of n. https://en.wikipedia.org/wiki/Pointer_aliasing

n[2]++; ASCII char values can be manipulated by arithmetic operators in C++. Look at an ASCII table to see what value each character has as an integer http://www.asciitable.com/

http://coliru.stacked-crooked.com/a/0a95ea981abfdb8b
Topic archived. No new replies allowed.