Get length of dynamically allocated array in C

Possible duplicate:
array length in function argument

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

I tried:

sizeof(ptr)
sizeof(ptr + 100)

and they didn’t work.

+3
source share
4 answers

You can not. You must pass the length as a parameter to your function. The size of the pointer is the size of the variable containing the address, this is the reason 4 (32-bit address space) that you found.

+20
source

Since malloc simply returns a block of memory, you can add additional information to the block telling how many elements are in the array, this is one way if you cannot add an argument that tells the size of the array

eg.

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

, PHP, , .

+5

Here you see the dangers of C: a ptr just points to memory and does not know what the estimated size is. You can simply zoom in and out, and the OS may eventually complain, or you crash your program, or corrupt others. You should always specify the size and determine the boundaries yourself.

+2
source

Source: https://habr.com/ru/post/1794897/


All Articles