结构指针未在 sizeof() 方法中提供正确的大小
使用 malloc 或 realloc 分配内存后获取结构指针的大小时遇到问题。我通过在单独的计数器中跟踪内存来解决这个问题,但我想知道这是否是一个错误,或者是否有一种方法可以正确查询结构指针的大小。
示例代码演示了无论我分配给结构体指针多少内存,在使用 sizeof() 方法查询时它总是返回 4。
typedef struct {
int modelID;
int bufferPosition;
int bufferSize;
} Model;
Model *models = malloc(10000 * sizeof(Model));
NSLog(@"sizeof(models) = %lu", sizeof(models)); //this prints: sizeof(models) = 4
I'm having a issue getting the size of a struct pointer after allocating the memory using malloc or realloc. I've worked around this by keeping track of the memory in a separate counter, but I would like to know if this is a bug or if there is a way to properly query the size of a struct pointer.
Sample code demonstrates that no matter how much memory I allocate to the struct pointer it always returns 4 when querying using the sizeof() method.
typedef struct {
int modelID;
int bufferPosition;
int bufferSize;
} Model;
Model *models = malloc(10000 * sizeof(Model));
NSLog(@"sizeof(models) = %lu", sizeof(models)); //this prints: sizeof(models) = 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
4是正确答案,因为“models”是一个指针,而指针有4个字节。您将无法通过这种方式找到数组的长度。你不使用 NSArray 有什么原因吗?
4 is the correct answer, because "models" is a pointer, and pointers are 4 bytes. You will not be able to find the length of an array this way. Any reason you're not using NSArray?
如果我理解正确的话,您想要获取分配的缓冲区的大小。
sizeof
如果是错误的方式,因为它是在编译时评估的。缓冲区的大小是一个运行时概念。您需要一种方法来查询 C 库以返回指向缓冲区的指针的分配大小。
有些系统有办法获取此类信息,例如 Mac OS 上的
malloc_size
。If I understand you correctly you want to get at the size of the allocated buffer.
sizeof
if the wrong way to go since it is evaluated at compile time. The size of the buffer is a runtime concept.You would need a way to query you C library to return the allocation size for the pointer to the buffer.
Some systems have a way to get that kind of information, for instance
malloc_size
on Mac OS.4 是正确答案。
指针指向可以包含任何内容的内存位置。当您查询指针的大小时,它会给出保存指针的内存位置的大小,在您的情况下为 4。
例如
,在上面的情况下,a 和 b 都具有相同的大小,无论它们在哪里指向。
有关更多信息,请查看这篇文章指针的大小
4 is the correct answer.
Pointers point to a memory location which could contain anything. When you are querying the size of a pointer, it gives the size of the memory location which holds the pointer, which in your case is 4.
For example
In the above case, both a and b have the same size irrespective of where they are pointing to.
For more information, have a look at this post size of a pointer
sizeof(myvar)
将返回指针的大小。在32位环境中它等于4(字节)。为什么不使用
sizeof (Model)
来代替呢?sizeof(myvar)
will return size of pointer. in 32bit environment it equals to 4(bytes).why don't you use
sizeof (Model)
instead?