iterating in a array in C

前端 未结 4 1819
南笙
南笙 2020-12-11 12:06

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

4条回答
  •  抹茶落季
    2020-12-11 13:02

    You can reserve the first element of array to store the size

    #include 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题