Using strings or pointers to strings in struct

43 Views Asked by At

I think I am missing something critical and I can't find an answer. If I want to use string in struct, is it better to use char arrays or pointers to them? Following code works as intended, but raises warnings "Warning C4047 'function': 'const char ' differs in levels of indirection from 'char ()[3]"

when used with following definition of struct

typedef struct element {
    char name[20];
    char symb[3];
    double wt;
}element;

And following procedure for creating element

element e;
char name[20];
char symbol[3];
scanf("%s %s %lf", &name, &symbol, &e.wt);
strcpy(&e.name, &name);
strcpy(&e.symb, &symbol);
1

There are 1 best solutions below

1
On

Check the data types.

Change

 strcpy(&e.name, &name);

to

 strcpy(e.name, name);

and

scanf("%s %s %lf", &name, &symbol, &e.wt);

to

scanf("%s %s %lf", name, symbol, &e.wt);

That said, it's better to use fgets() to take user input. If you have to use scanf(), you must check for success of the scanf() call before using the scanned values.