Search code examples
cdynamic-memory-allocation

Can I iterate dynamic array without knowing the size of it


I allocated some data in a dynamic array of a struct. Can I iterate that struct * without knowing it's size somehow?

Would this work?

int main() {
    struct *foo = NULL;

    //struct filling

    iterate_foo(foo);
}

void iterate_foo(struct *foo) {
    int i=0;
 
    while (foo[i] != NULL) {    // Would this work?

        //something
    }
}

Solution

  • The only way that can work is if you have a sentinel value in the array that indicates the end. Strings in C work that way.

    For instance, if you invoke strcpy(a, b), then characters from b will be copied to a until and including the value zero. If there's no zero terminator within the b array, or if a is not big enough to hold all the characters, the function call leads to undefined behavior.

    If you don't want to use a sentinel value, you have the option of passing the size as a separate parameter. Another way is to wrap things in a container struct, like this:

    struct container {
        struct mystruct *data;
        size_t size;
    }
    

    Furthermore, struct *foo = NULL; is wrong. It has to be something like struct mystruct *foo = NULL;

    But if you have this code:

    void foo(T *ptr) {
        // Do something
    }
    
    int main(void) {
        T *a = malloc(N * sizeof *a);
        T b[N];
        foo(a);
        foo(b);
    }
    

    Then it's completely impossible for foo to figure out N in a portable way. In some cases, believe that the implementation of malloc stores the size right before the data. But don't try to exploit that. It will only cause severe head ache.