简体   繁体   中英

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.
2) Later I want to get the size of this buffer in BYTES. The 2nd line will do this job.

sizeof returns the size required by the type. Since the type you pass to sizeof in this case is pointer, it will return size of the pointer.

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

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. so sizeof(ptr0) will return 4 or 8 bytes typically. instead use strlen ? or actually store the no. of bytes held by the (void *) in a separate variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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