简体   繁体   English

在结构中使用字符串或指向字符串的指针

[英]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?如果我想在结构中使用字符串,最好使用 char arrays 还是指向它们的指针? Following code works as intended, but raises warnings "Warning C4047 'function': 'const char ' differs in levels of indirection from 'char ( )[3]"以下代码按预期工作,但会引发警告“警告 C4047 'function': 'const char ' 在间接级别上与 '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.也就是说,最好使用fgets()来获取用户输入。 If you have to use scanf() , you must check for success of the scanf() call before using the scanned values.如果必须使用scanf() ,则必须在使用扫描值之前检查scanf()调用是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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