Search code examples
cstructarr

Arrays in Structs passed into functions


I'm very new to C, which I just started learning. Apologies if this question seems kind of dumb.

Can someone please explain why this doesn't work? Is there any way to accomplish something like this? Thanks so much!

struct test{
    int arr[10];
};

void foo(struct test t){
    t.arr[0] = 1;
}

int main() {
    struct test t = {malloc(10*sizeof(int))};
    foo(t);
    printf("%d", t.arr[0]);
}

I'm not sure exactly why the t.arr[0] isn't assigned to 1.


Solution

  • You need to pass the pointer to the structure to function foo() to allow foo() to update the structure t. I have updated your code at various points with comments. Please also note that malloc() is not required for structure t because of the way it is declared... the OS will set aside stack space for the structure. If you had declared only a pointer of type struct t, then yes, you would need malloc().

    Runnable code available here.

    #include <stdlib.h>
    #include <stdio.h>
    
    struct test{
        int arr[10];
    };
    
    void foo(struct test *t){  /* updated: pointer of type struct t */
        t->arr[0] = 1;      /* updated. Access pointer struct members like this ( -> ) -- not the dot syntax */
    }
    
    int main() {
        struct test t;  /*updated -- this declaration already allocates space for the array in t -- see output from printf() */
        foo(&t);    /* updated -- foo() needs a pointer to the struct.  So we pass the address of t (&t) */
        printf("t.arr[0] = %d\nsizeof(t) = %d\n", t.arr[0], sizeof(t));
    }
    

    Output:

    t.arr[0] = 1  /* It works! */
    sizeof(t) = 40  /* See?  40 bytes allocated already (on my platform). */