开发者

space complexity [closed]

开发者 https://www.devze.com 2023-01-02 17:55 出处:网络
It's difficult to tell what is being asked here. This question is ambi开发者_开发技巧guous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form.
It's difficult to tell what is being asked here. This question is ambi开发者_开发技巧guous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 (*)()))
{
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消