how sure can we be those bytes will always be in a sequential order?
If you initialize the pointer using a string you can be 100% sure the bytes will be in sequential order. You're guaranteed that *name will be P, *(name+1) will be 'a', *(name+2) will be 'u' and so on.
And, how sure can we be that the character at position name+13 is always '\0'?
name+13 will add 13 to the address that's stored in name. But the byte at name+13 will not be '\0'. It will be at name+12:
Code:
name | name+1 | name+2 | name+3 | ... | name+10 | name+11 | name+12 |
P a u l ... l l \0
When you use pointer arithmetic, the size of the data that the pointer points to comes into play. If you have an int pointer, then ptr+3 will actually be ptr plus sizeof(int)*3 for instance. This is very convenient for stepping through any kind of array using a pointer:
Code:
int array[] = { 0, 1, 2, 3 };
int *ptr = array;
In the code above, if array starts at memory address 10, then ptr will evaluate to 10, ptr+1 will point to address 10+sizeof(int)*1, ptr+2 will point to address 10+sizeof(int)*2, and so on. Even if you have a pointer to an array of structs, every time you add 1 to the pointer it will add the size of the struct to the memory address automatically. This way you can always be sure that ptr+1 will always point to array[1], ptr+2 will always point to array[2], etc.
This means you can also trick the compiler into letting you use a certain data type in a different way than you'd normally be able to. For instance:
Code:
#include <stdio.h>
int main(void)
{
int num = 0x12345678;
char *ptr = (char *)#
printf("num = %X\n\n", num);
printf("byte 1: %X\n", ptr[0]);
printf("byte 2: %X\n", ptr[1]);
printf("byte 3: %X\n", ptr[2]);
printf("byte 4: %X\n", ptr[3]);
return 0;
}
Code:
num = 12345678
byte 1: 78
byte 2: 56
byte 3: 34
byte 4: 12
By tricking the compiler by using a pointer to char that actually points to an int, it will step through the number sizeof(char) bytes at a time instead of sizeof(int) bytes at a time. You can easily see from the results that I'm on a little endian machine since the MSB of num is stored in the last byte intead of the first one.