Using sizeof with array?


I'm trying to calculate the size of values I've dynamically allocated memory to, i.e.

col_ind = new long[nz];
row_ptr = new long[inrows+1];
val = new double[nz];

from pointers. Now I've created the function,

int getmemsize(int i) {
	int sizes[3];
	sizes[0] = sizeof val;
	sizes[1] = sizeof col_ind;
	sizes[2] = sizeof row_ptr;
	return sizes[i];

but each one is returning just the value 4? My arrays (one example) look like:

val = [ 5 2 5 9 8 3 9 10 9 ]
col_ind = [ 0 1 1 ]
row_ptr = [ 0 2 3 ]

Thanks for your help!
Probably , it prints the pointer size , because as you know if you refere array name , it is hold array's zero base adress.
If you want to find the array size you have to iterate.
Last edited on
but each one is returning just the value 4?
Yes, thats the size of the pointer.

you need to pass the number of elements in the array separately or you use vector:
Ah, so in essence, it would be 4* the no of elements?
I don't know what you mean by that, but you cannot determine the size of a dynamically allocated array with sizeof

4 == sizeof(long *) (or sizeof(whatever *))
It all shows the same, because name of an array is a pointer to its first element. SIZEs of types of variables may be different in comparison with another computers and for your PC both long and double eat the same portion of memory. So when you write sizeof(row_ptr) and sizeof(val) it's the same as if you write sizeof(long) or sizeof(double)

But I think there is no way to determine size of dynamically allocated array (vectors are recommended)
Last edited on
Ah, it's part of a (very long) assignment to return the size. I'll just assume I have to return sizeof the pointer type, * the size of the array, as that's all I really can do I guess.

Thanks for the input guys.
Topic archived. No new replies allowed.