简体   繁体   中英

Using strings or pointers to strings in struct

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM