How to know the end of int* array?

2020-06-03 08:30发布

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?

标签: c arrays int
5条回答
走好不送
2楼-- · 2020-06-03 08:42

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.

查看更多
家丑人穷心不美
3楼-- · 2020-06-03 08:43

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.

查看更多
We Are One
4楼-- · 2020-06-03 08:44

C doesn't manage array lengths, as some other languages do.

you might consider a 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 };
查看更多
Melony?
5楼-- · 2020-06-03 08:52

C does not know where is the end of your dynamic array. you should remember the size that you allocate for the array.

查看更多
Animai°情兽
6楼-- · 2020-06-03 09:04

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.

查看更多
登录 后发表回答