简体   繁体   中英

Getting error in following c code [Segmentation fault]

Getting segmentation fault when using *s instead of 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.

#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 * .
  • o , a , b are of type char
  • j is of type char [20] (array).

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 .

Suggestion:

  1. Always prefer int main(void) over main() .
  2. Enable compiler warnings and pay heed to them.

Related reading: From C11 standard, chapter §7.21.6.1, fprintf() function (emphasis mine)

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.

In your code, a and b are character variables not a string. Change your printf into like this.

%c is format specifier for character.

printf("Code Generated:%s %c , %c\n",s,a,b);

You have to allocate the memory for pointer variable char *s . And assign the value to that variable using strcpy .

s=malloc(30);
strcpy(s,"ADD");

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