Search code examples
cstringgccstrcmp

If statement looks acceptable, but has error: expected expression before ‘)’ token


I have minimized my code to just what is necessary to reproduce this error. I have what I believe is a perfectly fine if statement, but gcc insists that it is not a valid statement.

#define SOMECHAR *

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char* my_string = (char*) malloc(sizeof(char[5]));
    strcpy(my_string, "aa*a");
    int i;

    for (i=0; i< sizeof(my_string); i++){
        if(strcmp(&my_string[i], SOMECHAR) == 0){
            printf("%s", "b");
        } else {
            printf("%s", &my_string[i]);
        }   
    }
}

Solution

  • Thanks to your comments and suggestions, I figured out what I really wanted. The first problem is to #define a character, it needs to be in single quotes. And sizeof() is totally for describing the size of a pointer, not how long it is. I should be using strlen(). Rookie mistake. And my main method here doesn't have a return, so that would be a problem once fixing the error I already had.

    But there's a much better way to do what I needed without looping and condition checking. In string.h there is a function called strchr that will return a pointer to the last character in a string before matching a given character. I've modified my code like this:

    #define SOMECHAR '*'
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(){
        char* line = (char*) malloc(sizeof(char[5]));
        strcpy(line, "aa*a");
        int i;
        char* ending;
    
        printf("%s\n", line);
        ending = strchr(line, SOMECHAR);
        ending[0] = '\0';
        printf("%s\n", line);
    
        return 0;
    }
    

    This terminates a given string at the character before the match. Which is what my assignment requires. Thanks all for your help.