Why does it show that my function returns an int when it returns a char*?

StackOverflow https://stackoverflow.com/questions/19615369

  •  01-07-2022
  •  | 
  •  

سؤال

The yacc code:

    %{
            #include<stdio.h>
        #include<string.h>



    %}

    %union {
                    char* dval;

            }

    %token <dval> NUM VAR
    %type <dval> E P
    %left '+' '-'
    %left '*' '/'

    %%
    statement : P {printf("\nt = %s\n \n",$1);}
              ;
    P: E
       ;

    E : E '+' E {strcpy($$,gencode($1,"+",$3));}
      | E '-' E {strcpy($$,gencode($1,"-",$3));}
      | E '*' E {strcpy($$,gencode($1,"*",$3));}
      | E '/' E {strcpy($$,gencode($1,"/",$3));}
      | '(' E ')' {strcpy($$,$2);}
      | NUM {strcpy($$,$1);}
      | VAR {strcpy($$,$1);}
      ;
    %%

**The lex code:**


   %{
            #include<stdio.h>
        #include<stdlib.h>
        #include<string.h>
            #include"y.tab.h"
        int n=0;
        char *ch="t";


    %}
    %%
    [0-9]+ {strcpy(yylval.dval,yytext); return NUM;}
    [a-z]+ {strcpy(yylval.dval,yytext); return VAR;}
    \n {return 0;}
    . {return yytext[0];}
    %%
    void yyerror(char* str)
    {
            printf("\n%s",str);
    }

    char* gencode(char *first,char *op,char *second)
    {
        char  *t;
        char x[5];
        t=(char*) malloc(sizeof(char)*5);

        strcpy(t, ch);
        itoa(n, x);
        strcat(t, x);        
        printf("\n%s = %s %s %s\n",t,first,op,second);
        n++;
        t[strlen(t)]='\0';

        return t;
    }

    main()
    {
            yyparse();
            return 0;
    }

For some reason gcc outputs the error: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]. Where as the second argument of strcpy is the function gencode which returns a char* and not an integer.

هل كانت مفيدة؟

المحلول

You need to declare gencode in the beginning of the yacc file. Otherwise, the compiler sees it as undefined and assumes it returns an int.

نصائح أخرى

You need to declare gencode in the .y file, either in a header you #include or directly in the .y file.

You have a much bigger problem, in that you declare dval (the type used for most rules) as a char *, but then you never initialize it to anything before writing to it with strcpy, so your code will crash (or worse) when strcpy tries to write to random addresses. You can fix this by replacing the strcpy calls in the lex file with yylval.dval = strdup(yytext) and the calls in the yacc file with just assignments to $$ (so $$ = gencode(... or whatever)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top