#include<stdio.h>
int main()
{
int *p=0;
char *ch=0;
p++;
ch++;
printf ("%d and %d\n",p,ch);
return 0;
}
Output:
4 and 1
-
I know the char pointer increments as +1 in the address that it is pointing too.
-
I know the pointer to an int increments as +4 in the address in gcc that it is pointing too.
-
I know Derefrencing a pointer should be done by the use of * with the pointer.
Queries:
-
Why is this not giving any garbage value for p and ch as both are pointers and has not assigned any address;
-
Why is this giving me the address difference that the respective pointer has obtained while incrementing, or is this a undefined behavior.
3.Why is the output 4 and 1?
Pl. Explain.
I have compiled this code on gcc-4.3.4.
Its a C code.
I am sorry if this comes out to be a copy of some question as I was not able to find any such question on stackoverflow.
First, your code is printing pointers as integers. While this is probably what you’re trying to do, it is not defined behavior, as it is entirely unportable on platforms where the size of a pointer (in bytes) is not the same as the size of
int. if you want to print pointer values, use%pinstead.To answer your questions. You are assigning values to both pointers: 0, which is synonymous with NULL.
Second. The reason you’re getting 4 1 is due to the size of an
intvs the size of acharon your platform. The char is going to be 1. On your platform, anintis 4 bytes wide. When incrementing a pointer the compiler will automatically move the address it references by the byte-count of the underlying type it represents.EDIT: you’re going to get the similar results, but with a supported print statement, do this instead:
Output (on my Mac) is: