Hey I have something of this type
eph_t *a;
The type is eph_t as you can see. Its an array in C but I do not know the size of the array nor
A pointer in C is just an address. When used as an array, you have to figure out (by some other means) the length of the array.
A lot of libraries dealing with arrays have functions accepting both the pointer to the array and its size. For example qsort(3) wants a second nmemb
argument giving the number of elements of the array base
(first argument to qsort
) to be sorted.
Alternatively, instead of passing just a pointer, you could use flexible array members (in C99) and pass (and return, when relevant) a pointer to a structure like
struct eph_tuple_st {
unsigned len;
eph_t* ptrtab[];
};
with the convention that the flexible array ptrtab
field has len
elements.
At last, as others suggested, you could use a sentinel value (i.e. a null word) to end the array. Generally I don't recommend that (risk of buffer overflow, time complexity to compute the actual size).
FWIW, recent C++ have std::dynarray (C++2014) and std::vector, and Ocaml has the Array module. You could switch to some more friendly programming language.
As others have said, it is unsafe to iterate over an array when you do not know the end of the array. This is often worked around in the following way.
int a[10];
) for example. you can use the sizeof
operator to determine the array's size. Please note this WILL NOT WORK when passing a pointer to an array to a function.memset
is a good example)So if you are designing a function that takes an array as a parameter, please use the above patterns. If you are using a function that does not use one of the above pattern, report the problem to the library designer as a bug.
If you do not know the size of the array then it is unsafe to iterate over it. Any time that you attempt to read elements beyond the last one you will get undefined behaviour. There is nothing safe you can do unless you know the size of the array.
You can reserve the first element of array to store the size
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int x, y;
double z;
} eph_t;
static void temp(eph_t *a)
{
size_t n;
memcpy(&n, a - 1, sizeof(size_t)); /* get size (stored in a - 1) */
printf("Count = %zu\n", n);
}
int main(void)
{
const size_t n = 5;
eph_t a[n + 1]; /* allocate space for 1 more element */
memcpy(&a[0], &n, sizeof(size_t)); /* now the first element contains n */
temp(a + 1); /* skip first element */
return 0;
}