简体   繁体   English

在以下c代码中出现错误[分段错误]

[英]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 * . schar *类型。
  • o , a , b are of type char oabchar类型
  • 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: 建议:

  1. Always prefer int main(void) over main() . 始终首选int main(void)胜过main()
  2. Enable compiler warnings and pay heed to them. 启用编译器警告并留意它们。

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. ab不是字符串(= char* ),而是chars。

In your code, a and b are character variables not a string. 在您的代码中, ab是字符变量,而不是字符串。 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.

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