Home > Software design >  Why is the compiler trying to convert char * into char? [closed]
Why is the compiler trying to convert char * into char? [closed]

Time:09-16

I am having trouble instantiating a struct due to the string/char array.

Here is my struct:

struct Drink {
    char name[10];
    int volume;
    double price;
    int quantity;
};

and here is where I am getting the error:

void loadDrinksFromFile(const char* filename) {
    FILE *fp;
    fp = fopen(filename, "r");
    int count = 0;
    char name[10];
    int volume;
    double price;
    int quantity;

    while (fscanf(fp, "%s %d %lf %d", name, &volume, &price, &quantity) != EOF) {
        // name is the cause of the error
        machine[count  ] = Drink{ name, volume, price, quantity };
    }
    fclose(fp);
}

It says a value of type char * cannot be used to initialize the entity of type char. Why is my code trying to receive a char type in the first place? My struct is expecting char name[10] which is an array of chars and I am passing an array of chars. I tried adding * and &, which I believe does not make sense either, but still it did not work.

Can someone help me understand this?

CodePudding user response:

Because neither C nor C support direct assignment of an existing raw array. Both allow to initialize an array with initializer list {x,y,z...} or string literals though.

E.g. int foo[] = {1,2,3}; is ok but int foo[12]{}; int bar[12]=foo; is not.

Just use std::array<T,N> as it has the desired semantics. Or better std::string for char arrays.

CodePudding user response:

If you're trying to use a compound literal, the syntax looks like a cast followed by an initializer list:

machine[count  ] = (struct Drink){ name, volume, price, quantity };

However, this still won't work because an array can't be used as an initializer.

In this case, you're better off writing to the struct fields directly from fscanf.

    while (fscanf(fp, "%s %d %lf %d", machine[count].name, &machine[count].volume, 
                  &machine[count].price, &machine[count].quantity) == 4) {
        count  ;
    }
  • Related