I'm making a dynamic array with int*
data type using malloc()
. But the problems is, how to know end of array?
There no an equivalent to \0
for int*
data type,so, how to do this? Pass size as out parameter of function?
I'm making a dynamic array with int*
data type using malloc()
. But the problems is, how to know end of array?
There no an equivalent to \0
for int*
data type,so, how to do this? Pass size as out parameter of function?
when u allocate memory with malloc, the number of bytes allocated is stored just before the start of the 'malloc'ated memory. if you know the size, you know the end as well! This is explained in the bible of C, the K&R book. Wish I could give you the page number as well, but you'll know it when u see it.
There is no "official" equivalent to
\0
for integers, but you can certainly use your own value. For example, if your integers represent distances then you can use -1 (not a valid distance) as a sentinel value to indicate the end of the array.If your integer array can reasonably contain any
int
value, then you can pass back the size of the allocated array with an additional parameter to your function.C doesn't manage array lengths, as some other languages do.
you might consider a structure for this:
in use:
C does not know where is the end of your dynamic array. you should remember the size that you allocate for the array.
You can use
NULL
as an end value. You can add an integer to a struct with the array that tracks the number of entries. Or you can track the size separately. You can do it however you want.