So, I am practicing pointers in detail. I just studied that if we perform operations like -
int a = 1025;
int *ptr = &a;
printf("The size of integer is = %d\n", sizeof(int));
printf("The address = %d, value = %d\n", ptr, *ptr);
printf("The address = %d, value = %d\n", ptr+1, *(ptr+1));
char *pointer;
pointer = ptr;
printf("The size of character is = %d\n", sizeof(char));
printf("The address = %d, value = %d\n", pointer, *pointer);
printf("The address = %d, value = %d\n", pointer+1, *(pointer+1));
This should throw an error in pointer = ptr;
because they have a different type, and the way to make this work is by typcasting int *ptr
to (char*)ptr
.
But somehow, this is working without type casting and here is the output-
The size of integer is = 4
The address = 15647756, value = 1025
The address = 15647760, value = 15647756
The size of character is = 1
The address = 15647756, value = 1
The address = 15647757, value = 4
Why is this working, and not showing an error?
Also, we know that Void Pointers cannot be incremented, like we cannot do void pointer + 1
but when I run this-
int a = 1025;
int *ptr = &a;
printf("The address = %d, value = %d\n", ptr, *ptr);
void *ptr1;
ptr1 = ptr;
printf("%d\n", ptr1+1);
It returns -
The address = 15647756, value = 1025
15647757
Clearly, the void pointer is getting incremented, which should NOT happen, Please explain this as well?
I am using gcc 9.4.0 version compiler on an 20.04 LTS ubuntu machine.