7

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.

Community
  • 1
  • 1
kranthi117
  • 628
  • 1
  • 8
  • 21
  • In C, don't cast the return value of malloc(). See http://stackoverflow.com/questions/953112/should-i-explicitly-cast-mallocs-return-value. – unwind Feb 26 '11 at 19:22

4 Answers4

28

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.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
8

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.

AndersK
  • 35,813
  • 6
  • 60
  • 86
  • 1
    You'd only add one byte to the the allocation to store the length? What if the allocation was 1000 instead of 10? – selbie Feb 26 '11 at 11:41
3

Here you see the dangers of C: a ptr just points to memory and has no way of knowing what supposed size is. You can just increment and increment and the OS might complain eventually, or you crash your program, or corrupt other ones. You should always specify the size, and check bounds yourself!

Henno Brandsma
  • 2,116
  • 11
  • 12
2

This is similar to Using pointer for crossing over all elements in INTEGER array

See my answer here

Community
  • 1
  • 1
datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • I think this is the approach used in [Go slices](https://tour.golang.org/moretypes/7). I think that is ok. – Ferrarezi Jan 08 '20 at 15:27