-2

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

2 Answers2

0

First, size_of(my_string) is size of a pointer, not size of array it point to.

Next, strcmp(&my_string[i], SOMECHAR) will be expanded to strcmp(&my_string[i], *), you need to:

#define SOMECHAR "*"

However, I believe you want this instead:

    if(my_string[i] == '*'){
        putchar('b');
    } else {
        putchar(my_string[i]);
    }  

And as M.M said in comment, you leak the memory you allocated

If you really need to define that character, simply do this:

#define SOMECHAR '*'

/*some other code */

    if(my_string[i] == SOMECHAR){
        putchar('b');
    } else {
        putchar(my_string[i]);
    } 
Danh
  • 5,916
  • 7
  • 30
  • 45
0

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.