0
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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
codeLover
  • 3,720
  • 10
  • 65
  • 121
  • What you are asking is not only not what happens, but it's literally impossible. Consider, for example, if `ptr0` points to two distinct objects that have the same beginning contents (say either a single integer or an array of two integers). How could `sizeof` know which object you wanted the size of? – David Schwartz Nov 05 '12 at 07:41
  • Just use std::string or std::vector, you're trying to do things the hard way. – john Nov 05 '12 at 08:17

3 Answers3

7

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I would add that if you need to see the size of string, instead of a pointer use an array i.e. char arr[] = "string"; then sizeof(arr) would return the length of string – fkl Nov 05 '12 at 07:51
  • 1
    @fayyazkl: I would rather add: [What is the difference between char a\[\] = “string”; and char *p = “string”;](http://stackoverflow.com/questions/9460260/what-is-the-difference-between-char-a-string-and-char-p-string/9631091#9631091) – Alok Save Nov 05 '12 at 07:54
2

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
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
1

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.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78