To start with it is important to notice that your code has undefined behavior. That means that we can not say anything about the generated output solely by referring to the C standard. The output may/will differ from system to system and some systems may not even be able to execute the code.
The problem is that you have a number of char
(a char
array) but you access it using an int
pointer. That is not allowed.
However, on a specific system (your system) it is possible to do some consideration about why the output looks as it does. But do remember that it is not valid C code. note: As pointed out by Antti Haapala the code syntax is valid - it's just the behavior of the program which is undefined
The string (aka char array) will be placed somewhere in memory like:
Address | Bin | Hex | Dec | Ascii char
--------------------------------------------
base | 0100 0001 | 41 | 65 | A
base+1 | 0100 0010 | 42 | 66 | B
base+2 | 0100 0011 | 43 | 67 | C
base+3 | 0100 0100 | 44 | 68 | D
base+4 | 0100 0101 | 45 | 69 | E
and so on
Notice that the memory holds binary values. The Hex, Dec, Ascii columns are just a "human" view of the same binary value.
Your pointer s
has the value base
, i.e. it points to the memory location that holds the value 0100 0001
(aka A).
Then you make ptr
point to base
as well.
When printing (i.e. printf("%c %d\n",*(ptr+1),*(ptr+1));
), the ptr+1
will point to a location that depends on the size of integers (which differs from system to system). Since you have size of int being 2, ptr+1
is the location base + 2
, i.e. 0100 0011
(aka C).
So the first part of this statement:
printf("%c %d\n",*(ptr+1),*(ptr+1));
^^ ^^^^^^^^
prints a C
, i.e. the char at location base+2
.
The second part
printf("%c %d\n",*(ptr+1),*(ptr+1));
^^ ^^^^^^^^
prints the integer value located at base+2
. (note - which is illegal as there is no integer there but let's forget that for a moment).
In your case int
is two bytes. So the used bytes will be the C
(hex: 0x43) and the D
(hex: 0x44). The value printed will depend on the endianness of your system.
Big endian (MSB first) will give:
0x4344 which is 17220 in decimal
Little endian (LSB first) will give:
0x4443 which is 17475 in decimal
So from this it seems your system is little endian.
As you can see a lot of this stuff is very system dependant and from a C standard point of view it is impossible to tell what the out will be.