[英]Getting error in following c code [Segmentation fault]
Getting segmentation fault when using *s
instead of char s
. 使用
*s
代替char s
时出现分段错误。 if I change *s
to s
I get error named char
pointer to integer.Please help me find the error.I also Googled but was not able to get it corrected. 如果我将
*s
更改为s
则会得到名为char
指向整数的指针的错误。请帮助我找到错误。我也用Google搜索但无法纠正它。
#include<stdio.h>
main()
{
char *s,o,a,b,j[20];
printf("code generation\n----------------------");
printf("Enter the code:\n");
scanf("%s",j);
int c=1;
while(c==1){
o=j[1];
a=j[0];
b=j[2];
switch(o){
case '+':
s="ADD";
break;
case '-':
s="SUB";
break;
case '*':
s="MUL";
break;
case '/':
s="DIV";
break;
case '=':
s="MOV";
break;
default:
s="INV";
}
printf("Code Generated:%s %s , %s\n",s,a,b);
}
}
For a definition like 对于像这样的定义
char *s,o,a,b,j[20];
s
is of type char *
. s
是char *
类型。 o
, a
, b
are of type char
o
, a
, b
为char
类型 j
is of type char [20]
(array). j
的类型为char [20]
(数组)。 So, you need to change your code 因此,您需要更改代码
printf("Code Generated:%s %s , %s\n",s,a,b);
to 至
printf("Code Generated:%s %c , %c\n",s,a,b);
as the correct format specifier for a char
is %c
. 因为
char
的正确格式说明符是%c
。
Suggestion: 建议:
int main(void)
over main()
. int main(void)
胜过main()
。 Related reading: From C11
standard, chapter §7.21.6.1, fprintf()
function (emphasis mine) 相关阅读:从
C11
标准的第§7.21.6.1章, fprintf()
函数(强调我的)
If a conversion specification is invalid, the behavior is undefined.
如果转换规范无效,则行为未定义。 If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
如果任何参数都不是相应转换规范的正确类型,则行为未定义。
And, a note about undefined behaviour . 并且,有关未定义行为的说明 。
Sounds a bit off topic, but this line : 听起来有点不合时宜,但这行:
printf("Code Generated:%s %s , %s\n",s,a,b);
a
and b
are not strings (= char*
), but chars. a
和b
不是字符串(= char*
),而是chars。
In your code, a
and b
are character variables not a string. 在您的代码中,
a
和b
是字符变量,而不是字符串。 Change your printf
into like this. 将您的
printf
更改为这样。
%c
is format specifier for character. %c
是字符的格式说明符。
printf("Code Generated:%s %c , %c\n",s,a,b);
You have to allocate the memory for pointer variable char *s
. 您必须为指针变量
char *s
分配内存。 And assign the value to that variable using strcpy
. 然后使用
strcpy
将值分配给该变量。
s=malloc(30);
strcpy(s,"ADD");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.