-1

If I declare an array inside the main() function and send that array into a function as a parameter, can I add elements to that array that aren't pointers created with malloc?

I understand that static variables created within a function are put on the stack and become unreliable after returning from the function. However, because the array is initialized as a static array within main(), the memory locations within the array should be preserved after returning from the helper function, no?

typedef struct test_t {
    int x,y;
} test;

void fillArray(test arr[], int length) {
    int i;
    for (i=0; i<length; i++) {
        arr[i] = (test){i,i*3}
    }
    return;
}

void main() {
    test arr[5];
    fillArray(arr, 5);
    int i;
    for (i=0; i<5; i++) {
        printf("(%d,%d)\n", arr[i].x, arr[i].y);
    }
}

I expect that this toy example will behave properly because there isn't much going on, but is this technically undefined behaviour or is this safe?

pattymills
  • 107
  • 1
  • 9

1 Answers1

0

In most contexts (*) arrays are converted to a pointer to their first element.

In your case, when used as a function argument, the array test arr[5] is converted to a pointer to its first element (to &arr[0]) of type test*. The contents of the pointed to objects are changeable and they retain the changes when control returns to main().

The only 3 things wrong with your code are

  1. missing #include <stdio.h>
  2. void main() should be int main(void)
  3. missing ; in the body of for inside fillArray()

(*) exceptions are when the array is used as argument of sizeof or & operator or when it's a string literal used to initialize an array object.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • "The contents of the pointed to objects are changeable and they retain the changes when control returns to main()." So even though I'm creating the structs within the helper function (and they aren't being created with malloc), they are still safe within main() because they are being stored in memory locations that were put on main()'s stack? – pattymills Jun 08 '19 at 19:20
  • You create the structs within `main()` with the *declaration* `test arr[5];`. At this time their **values** are indeterminate (`arr` elements have not been initialized), which is perfectly valid as long as you do not use those values. What you say is creating the structs if effectively assigning them a value. *Some (many (most (all?))) compilers will use the stack for `main()`'s variables,* but the use (or presence) of a "stack" is not required by the C standard. – pmg Jun 08 '19 at 20:21
  • ahhhhhhh I'm dumb, I didn't even think of the fact that the actual structs are being created with the array. thank you for sticking with me :) have a nice day – pattymills Jun 08 '19 at 20:25