Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to set a struct's inside array to be initialized in C

Tags:

arrays

c

struct

I have this struct definition:

typedef struct intArray
{
    int myArray[1000];
} intArray;

My goal is to create an intArray of zeros, i tried this:

intArray example;
int createArray[1000] = {0};
example.myArray = createArray;

This results in this error message:

error: assignment to expression with array type

I want the struct to automatically initialize the array to 0's but i understand it is not possible because it is only a type definition and not a variable. So i created one and created the array, just tried to assign it and this is the result. Any advice is appreciated.

like image 656
Eyzuky Avatar asked Dec 05 '25 18:12

Eyzuky


1 Answers

Why not use memset to zero the array? Also, as suggested by another user, it'd be better to allocate this memory to a pointer....especially if you intend to pass that struct around between functions.

Just a thought, but this would work:

typedef struct intArray {
    int *myArray;
} intArray;

int main(void)
{
    intArray a;
    int b;

    // malloc() and zero the array
    //         
    // Heh...yeah, always check return value -- thanks,
    // Bob__ - much obliged, sir.
    //              
    if ((a.myArray = calloc(1000, sizeof *a.myArray)) == NULL) {
        perror("malloc()");
        exit(EXIT_FAILURE);
    }

    memset(a.myArray, 0, (1000 * sizeof(int)));

    // Fill the array with some values
    //
    for (b = 0; b < 1000; b++)
        a.myArray[b] = b;

    // Just to make sure all is well...yep, this works.
    //
    for (b = 999; b >= 0; b--)
        fprintf(stdout, "myArray[%i] = %i\n", b, a.myArray[b]);

    free(a.myArray);

}
like image 91
Nunchy Avatar answered Dec 08 '25 12:12

Nunchy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!