Baratao00
Baratao00

Reputation: 21

Filling array of a struct, that was declared in .h, inside function in .c

Ok so I have this struct declared at my .h file:

typedef struct Vet32 {
    char key;
    int thrash[7];
} Vet32;

And I have one function in my other .c file, that is not my main.c, where I wanna fill my array thrash in one line like:

vector[i].thrash[] = { 1, 3, 9, 123, 85, 12, 875 };

But I always get errors from my gcc compiler when i try to fill my array like this. The function i use is:

void createVet(FILE* arq, Vet32 vector[22]) {
    for (int i = 0; i < 22; i++ ) {
        fscanf(arq, "%c", vector[i].key);
        vector[i].thrash[7] = { 1, 3, 9, 123, 85, 12, 875 };
    }
}

The lenght of the arrays are always that. Anyone can help me with this? it really annoys me this smalls errors in C xD.

Upvotes: 0

Views: 84

Answers (2)

user2371524
user2371524

Reputation:

What you have here is a syntax for initialization. Initialization gives a variable its initial value, and this value has to be constant at compile time. This is an important requirement as it allows the compiler to emit the value directly, e.g. in a data segment in the resulting binary.

But you try to use it in an assignment. An assignment changes the value of a variable at runtime.

For all versions of , it is impossible to assign to an array. So the most straight-forward way to do what you want to achieve is to assign each individual member:

vector[i].thrash[0] = 1;
vector[i].thrash[1] = 3;
[...]

But since you use a struct, there is another way. A struct can be assigned as a whole, and this can be done from a compound literal, IIRC starting from . Here's some example code illustrating this:

#include <stdio.h>
#include <stdlib.h>

typedef struct Vet32 {
    char key;
    int thrash[7];
} Vet32;


void initVet(Vet32 *self)
{
    *self = (Vet32) {
        .key = 0,
        .thrash = { 1, 3, 9, 123, 85, 12, 875 }
    };
}

int main(void)
{
    Vet32 vet;
    initVet(&vet);
    for (int i = 0; i < 7; ++i)
    {
        printf("vet[%d] = %d\n", i, vet.thrash[i]);
    }
    return 0;
}

The compound literal looks like an initializer, but prepended with an explicit notation of the type in parantheses, just like it was a cast.

Upvotes: 1

Toribio
Toribio

Reputation: 4078

You can only initialize arrays when declaring them. If you want to fill them out later, you need to use a loop or something like memcpy:

void createVet(FILE* arq, Vet32 vector[22]) {
    for (int i = 0; i < 22; i++ ) {
        fscanf(arq, "%c", &(vector[i].key));

        int values[7] = { 1, 3, 9, 123, 85, 12, 875 };
        for (int j = 0; j < 7; j++ ) {
            vector[i].thrash[j] = values[j];
        }
    }
}

With memcpy, instead of the new for loop I added earlier, you can do this:

int values[7] = { 1, 3, 9, 123, 85, 12, 875 };
memcpy(vector[i].thrash, values, sizeof(values));

Upvotes: 2

Related Questions