space complexity [closed]
how can i get the space taken by a pointer at run time
Imagine a type, which I will call 'type'. Might be an "int", might be a fancy structure.
type *p;
sizeof(p) = size of the pointer to p ( i.e., the number of bytes required to store the address that the data in 'p' is stored at. On a PC it's likely to be 4 or 8 bytes depending on if you have a 32bit or 64bit architecture, but that's not guaranteed. On other archetectures it could be pretty much anything )
sizeof(*p) = size of the type p; The number of bytes used to store the data in 'type'.
Important Note:
You might see code that does this:
p = malloc(sizeof(*p)+100)
In this case, enough memory will be allocated to store 'type' and an extra 100 bytes. However, doing a 'sizeof(*p)' will return the memory required by 'type', not the extra 100 bytes. There is no way in C to know how much memory has been allocated; you have to manage that yourself.
The question is somewhat ambiguous, but I think:
printf("Size of pointer is: %zu\n", sizeof(*p));
should do what you want. The %zu is used insted of %d as the pointer will be a unsigned integer size.
One thing to note is that you can do sizeof
on the type itself and not just on a variable:
// Check if the pointer size of a generic data pointer is different
// than the pointer size of a function
if (sizeof(void *) != sizeof(int (*)()))
{
...
}
精彩评论