Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the length of dynamically allocated array in C [duplicate]

Tags:

c

Possible Duplicate:
length of array in function argument

How do I get the length of a dynamically allocated array in C?

I tried:

sizeof(ptr)
sizeof(ptr + 100)

and they didn't work.

like image 487
kranthi117 Avatar asked Feb 26 '11 10:02

kranthi117


2 Answers

You can't. You have to pass the length as a parameter to your function. The size of a pointer is the size of a variable containing an address, this is the reason of 4 ( 32 bit address space ) you found.

like image 63
Felice Pollano Avatar answered Nov 15 '22 09:11

Felice Pollano


Since malloc just gives back a block of memory you could add extra information in the block telling how many elements are in the array, that is one way around if you cannot add an argument that tells the size of the array

e.g.

char* ptr = malloc( sizeof(double) * 10 + sizeof(char) );
*ptr++ = 10;
return (double*)ptr;

assuming you can read before the array in PHP, a language which I am not familiar with.

like image 28
AndersK Avatar answered Nov 15 '22 09:11

AndersK