How to know the end of an int * array?

I am making a dynamic array with an int* data type using malloc() . But the problems: how to find out the end of an array? there is no \0 equivalent for an int* data type, so how to do this? passage size as an external parameter of the function? Hope this is clear to you. Any help is greatly appreciated.

+7
source share
5 answers

C does not handle array lengths, as some other languages ​​do.

you can consider the structure for this:

 typedef struct t_thing { int* things; size_t count; } t_thing; 

in use:

 t_thing t = { (int*)malloc(sizeof(int) * n), n }; 
+11
source

There is no "official" equivalent of \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 reference value to indicate the end of the array.

If your integer array can reasonably contain any int value, you can pass the size of the selected array with an additional parameter to your function.

+8
source

You can use NULL as the final value. You can add an integer to the structure with an array that keeps track of the number of records. Or you can track the size separately. You can do it however you want.

0
source

C does not know where your dynamic array ends. you must remember the size you allocate for the array.

0
source

when u allocates memory using malloc, the number of bytes allocated is stored immediately before the start of "malloc'ated memory". if you know the size, you know the end too! This is explained in the Bible by books C and K. I wish that I can give you the page number, but you will know it when you see it.

0
source

All Articles