Advertisement

Using sizeof() on a dynamic array?

Started by December 21, 2000 09:54 PM
6 comments, last by Anthracks 24 years ago
In something I''m coding, I need to know the size of a dynamic array, allocated by the new operator (see below). My problem is that when I call sizeof() on the array, it just gives me the size of a char *, not the size of my array. Do I have to keep track of how big the array is on my own? Sizeof seems laregely uesless here.
  
char *Buf=new char[1024];

printf("Sizeof Buf: %d\n", sizeof(Buff));
// Prints "Sizeof Buf: 4"

  
Any ideas? Anthracks
sizeof (*Buf );

if ( there''''s a will )
return ( there''''s a way );
Advertisement
I actually tried that too, and it told me that the size is 1! Any other thoughts? I also tried sizeof(&Buf[0]) just for kicks, and got 4 again.

Anthracks
I actually tried that too, and it told me that the size is 1! Any other thoughts? I also tried sizeof(&Buf[0]) just for kicks, and got 4 again.

Anthracks
i forgot, sizeof (*buf ) will give you the size of the first byte of the array.


But i can tell you the size; it is 1024.

Really, don''t laught, the array is constant, and if you declare the array at run time, you must pass a variable like:

int variable = user input.


char *buf = new char[variable];

so the size is == variable.






if ( there''''s a will )
return ( there''''s a way );
The last reply is correct. The only way to know the size is by storing it in memory. Your original solution (sizeof( Array ))works only if the array is off of the stack or char Array[255].

ZooRaider
Advertisement
sizeof returns the size (in bytes) of the data element you give to it, not how much stuff it points at
Yes you must keep track of the size of the array on your own in C.

Many C++ array objects do this sort of bookkeeping for you, like MFC''s CString or CArray, and any stl container.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
i belive that you are programming in C/C++.


in C++:

if you declare a variable like:

int var = 11;

and a pointer.

int* ptr;

and then you make the pointer point to var.

ptr = &var

then:

*ptr == 11



just a matter of getting used to this weird syntax.

Edited by - myself on December 21, 2000 12:16:45 AM

Edited by - myself on December 21, 2000 12:31:48 AM

This topic is closed to new replies.

Advertisement