为什么我不能为我的struct变量赋一个char? [英] Why can't I assign a char to my struct variable?
本文介绍了为什么我不能为我的struct变量赋一个char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将单个字符分配给我的结构变量'autocorrect'但它不会让我给我这个错误:
main.c: 134:12:错误:预期的标识符或'('''之前'。'令牌
Settings.autocorrect ='n';
我不明白为什么。
我的尝试:
I am trying to assign a single char to my structure variable 'autocorrect' but it will not let me and gives me this error:
main.c:134:12: error: expected identifier or ‘(’ before ‘.’ token
Settings.autocorrect ='n';
I don't understand why.
What I have tried:
typedef struct Settings
{
char* dict_name;
int max_difference;
char autocorrect;
}Settings;
if(strstr(str, "autocorrect = yes"))
{
Settings.autocorrect = (char*)malloc(sizeof(char));
Settings.autocorrect = 'y';
}
else if(strstr(str, "autocorrect = no"))
{
Settings.autocorrect = (char*)malloc(sizeof(char));
Settings.autocorrect ='n';
}
}
推荐答案
设置是一个结构定义,而不是一个可以变量的变量旧数据:您需要创建一个变量来保存一个Settings结构,然后使用它来访问这些字段:
Settings is a struct definition, not a variable that can hold data: you need to create a variable to hold a Settings struct, and then use that to access the fields:
Settings set;
set.autocorrect = 'y';
或
Or
Settings *set = (Settings*) malloc(sizeof(Settings));
set->autocorrect = 'y';
您已将自动更正
声明为字符,但您尝试分配char *
到它。然后,您立即尝试用字符覆盖指针。将您的代码更改为:
You have declaredautocorrect
as a character and yet you try to assign achar*
to it. You then immediately try to overwrite the pointer with a character. Change your code to:
if(strstr(str, "autocorrect = yes"))
{
// space is automatically reserved for the character variable.
Settings.autocorrect = 'y';
}
else if(strstr(str, "autocorrect = no"))
{
Settings.autocorrect ='n';
}
}
您不需要为单个字符分配内存。仅适用于以NULL结尾的字符串。
删除
You don'ta need to allocate memory for a single char. Only for a NULL terminated string.
Remove the
malloc()
调用,它将起作用。
这篇关于为什么我不能为我的struct变量赋一个char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文