Hi everyone. Here's my code. My question is included in the comments:
1 2 3 4 5
int array[5];
int*ptr;
cout<<sizeof(array); //output is 20, as I expected.
ptr=newint[5];
cout<<sizeof(ptr); //output is 4. Why? Shouldn't it be the same output as line 3?
You are asking for the size of the pointer, not the object it is pointing to.
If you did cout << ptr; you'd get something like 0x804A1570 as an output. It's a memory address which on a 32-bit operating system is 32 bits (or 4 bytes).
You are asking for the size of the pointer, not the object it is pointing to.
I figured this was what it was doing. But then how can I get the size of the object that it's pointing to?
Ultimately, I want to find the length of the dynamically created integer array. I had originally intended to use sizeof(ptr) and then divide by sizeof(int) to get the length, but it seems that this is no longer possible. Any other ways?
There is no way to get the size of the array through the pointer. You have to remember the size somehow. You could have a separate variable that stores the size that you can use later.
1 2 3
int size = 5;
int *ptr=newint[size];
cout<<size;
You could also use std::vector that keeps track of the size for you, instead of the array.
So there is really know way to get the size of an array using a pointer?
Only way I can think of off hand is to set the last element to a sentinel value say -999 and iterate through and count. But that would be incredibly ugly to me, considering you need to know the size to create the array it shouldn't be an issue to remember it.
Something like this will: int array[] = {1,2,3,4,5,6,7,8,9,10}; // OK - compiler knows there's 10 elements
but not just int array[]; // error: storage size of 'array' isn't known
If you need the size of an array, count it yourself.
(or, if using dynamic memory, store the size in a variable)