polycarp
polycarp

Reputation: 13

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);

}



 }

Upvotes: 0

Views: 73

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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.

Upvotes: 2

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

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");

Upvotes: 0

Amessihel
Amessihel

Reputation: 6424

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.

Upvotes: 0

Related Questions