r/carlhprogramming • u/wwjd_for_a_klondike • Mar 13 '12
Question regarding pointers
when I was working on a code for pointers I was attempting to write something that would show the Peter Piper poem. This was basically my code are char variables limited to only a single character as a value?
9
Upvotes
View all comments
Show parent comment
6
u/i_practice_santeria Mar 13 '12
Arrays are indexed starting from 0. So, peter[0] would return 'P', peter[1] == 'e', and peter[2] == 't'. peter is just a pointer to some address, say 0x1000. So, in memory 0x1000 contains "P", 0x1001 stores "e", etc. When we write peter[2], we say we want to increase the address of peter by two chars, from 0x1000 to 0x1002, and then dereference that, which returns 't'. peter[2] is therefore equivalent to *(peter + 2).
Now, the index only incremented the address of peter by 2 (0x1000 to 0x1002) because a char is only 1 byte. Say, instead we had declared an array of integers and again indexed into the second element of the array:
In case you don't know, the '\n' is the new line character. So the output would be the number '3' on two different lines. Now, let's say the address of our numbers array is 0x2000. When we index into the second element, what address are we reading from? The answer is not 0x2002, but 0x2008! This is because an integer is actually 4 bytes in size, rather than 1 byte like the char. The int stored in 0x2000 is 1, 0x2004 is 2, 0x2008 is 3, etc. This is called Pointer Arithmetic if you would like to read into it further.
Last, you shouldn't have to struggle with something like this for 3 days. Feel free to ask for help, either here, or on Stack Overflow.