For instance in my 64-bit ubuntu machine, the length of pointer is 2 byte and have 1 memory address, so Does it always be the 2 byte, no matter such long int or int it pointe to?
if so, What’s the point to determine the type of data it point to? In the code below, except for incompatible warning purpose, how many bytes, the data represents, by use the %hu and %lu, so no matter the pointer is int or long, the result is the same. Could anyone give me a hint?
#include <stdio.h>
int main(void) {
int *ptr1;
long int *ptr2;
long int a = 0xffffffff;
ptr1 = &a;
ptr2 = &a;
printf("the value should the same as 2 ** 16 %hu", *ptr1);
printf("the value should the same as 2 ** 32 %lu", *ptr2);
return 0;
}
update:
another purpose of determining the type of pointer that I can think of is for the pointer arithmetic like:
ptr + 1, it will skip the length of byte the datatype has, instead of alway certain value
I may be misinterpreting what you’re asking, and if I am, please accept my apologies in advance. I think what’s happening is that your confusing the notion of pointers in general with the notion of the type that any given pointer may reference.
A pointer, regardless of the thing to which it points, is just an address in memory (however it is structured for a given environment or system). The type of data being referenced is critical in allocations (malloc, calloc, etc), because it does become important to know how many bytes of memory need to be allocated for a specific type/structure referenced by a given pointer. If you’re working with pointers to an array structure, the data size becomes even more critical if you increment a pointer reference, because the pointer increment can increment by the size of the data being referenced.
You can declare a pointer type, but it doesn’t allocate anything. And the warning you’re receiving is the compiler’s way of telling you that it sees that you have, deliberately or accidentally, taken the address of one type of variable, but are risking trying to use it as an address of a different kind of variable.
Let’s say an int takes four bytes, but a short int takes two. If you take a pointer to a short int, but write an int value to it, you’ll corrupt who knows what along the way. That’s precisely why its important to keep track of the kind of pointer you’re referencing, lest something Really Bad happens to your code at runtime.
As I said, I may be misunderstanding the problem, and if I am, please accept my apologies. I hope this is helpful.