RDGuida
RDGuida

Reputation: 566

Is there a way to calculate the size of a pointed vector through sizeof()?

Even if I write this statement

char *test= new char[35];

sizeof(test) will always return 4 (or another number depending on the system) rather than 35. I assume that this is because the size of a pointer is strictly the physical "pointing entity" and not the amount of memory reserved for that pointer. Is it correct?

Moreover, is there a way to retrieve the amount of memory reserved for a particular pointer using sizeof()?

Upvotes: 0

Views: 97

Answers (3)

JanCG
JanCG

Reputation: 105

As said in the other answers, from a normal pointer there is no way to know the amount of memory that has been reserved at the point where it is pointing to, because it is still pointing to garbage.

As soon as you fill the memory with a C-String you can get the length with strlen(test) because it looks for the end of string byte (0x0).

A better solution would be to use an array:

char test[35];
szie_t size = sizeof(test); //< returns 35

Upvotes: 0

Quentin
Quentin

Reputation: 63154

Nope.

Pointers are just plain variables (generally implemented as integer addresses) — that they can point to other objects is irrelevant to sizeof. Don't think about them as something "magic", that is somehow intimately bound to what they point to. Pointers are no more than a street number.

I'm bringing this up because of :

[...] the size of a pointer is strictly the physical "pointing entity" and not the amount of memory reserved for that pointer.

In your line of code :

  • An array of 35 chars is allocated in dynamic memory
  • Its first element's address is returned by new
  • You keep this address in test.

Note that any notion of array, or size thereof, has vanished before the second step. The pointer knows nothing about it. You know.

If you want to retrieve the size of the array, you'll need to keep track of it yourself in a separate variable, or use a class that does it for you, namely std::vector<char>.

Upvotes: 5

tenfour
tenfour

Reputation: 36896

I assume that this is because the size of a pointer is strictly the physical "pointing entity" and not the amount of memory reserved for that pointer. Is it correct?

Yes, this is correct; you are taking the sizeof() a pointer. A pointer is an address in memory; on 32-bit systems this will be 4 bytes. 64-bit systems it will be 8 bytes.

Moreover, is there a way to retrieve the amount of memory reserved for a particular pointer using sizeof()?

No. sizeof() knows nothing about what a pointer points at; it's a compile-time calculation. Getting this size will depend how it's been allocated.

In general you should be using std::vector<>. To get the size of a std::vector<>, use std::vector<>::size().

Upvotes: 4

Related Questions