简体   繁体   English

在指向C ++中的缓冲区(字符串“”)的空指针上使用sizeof()以便在BYTES中获得大小吗?

[英]Using sizeof() on a void pointer pointing to a buffer (string “ ”) in C++ in order to get the size in BYTES?

void * ptr0 = (void*)"Buffer_1";
int size0 = sizeof(ptr0);
// WILL THIS RETURN THE NUMBER OF BYTES OCCUPIED BY THE MEMORY POINTED BY ptr0?

My requirement is 我的要求是
1) store some data in buffer & create a void* pointer to it which I am doing in 1st line. 1)在缓冲区中存储一些数据并在第1行中创建指向它的void *指针。
2) Later I want to get the size of this buffer in BYTES. 2)稍后我想在BYTES中获取此缓冲区的大小。 The 2nd line will do this job. 第二行将完成此工作。

sizeof returns the size required by the type. sizeof返回类型所需的大小。 Since the type you pass to sizeof in this case is pointer, it will return size of the pointer. 由于在这种情况下您传递给sizeof的类型是指针,因此它将返回指针的大小。

If you need the size of the data pointed by a pointer you will have to remember it by storing it explicitly. 如果需要指针指向的数据大小,则必须通过显式存储它来记住它。

No this will simply return the size of your pointer in bytes. 不,这只会返回指针的大小(以字节为单位)。 Using sizeof to get the size of an array will only work on arrays declared like this 使用sizeof获取数组的大小仅适用于这样声明的数组

char szArray[10];

not on arrays created dynamically 不在动态创建的数组上

char* pArray = new char[10];

sizeof(szArray);  // number of elements * sizeof(char) = 10
sizeof(pArray);   // sizeof the pointer

sizeof() works at compile time. sizeof()在编译时起作用。 so sizeof(ptr0) will return 4 or 8 bytes typically. 因此sizeof(ptr0)通常返回4或8个字节。 instead use strlen ? 而是使用strlen吗? or actually store the no. 或实际存储编号 of bytes held by the (void *) in a separate variable. (void *)在单独的变量中保留的字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM