0

The strcmp cause the program to crash, Why is that? When removing strcmp it works well, and also with strcpy makes it crash

size_t maxLineLen=1024;
char *line = (char*)malloc(maxLineLen);
while(getline(&line, &maxLineLen,stdin)!= -1){
int h =strlen(line);
for (int i = 0; i < h; i++){
             if(strcmp(line[0], "a") == 0)  {
        printf("a found  %c \n ",line[i]);
            break;
        }

    }

}
return 0;
}
MFB
  • 105
  • 8
  • 3
    Note: They say [you shouldn't case the result of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT Feb 24 '16 at 14:01
  • 1
    `line[0]` is a `char`, not a `char *`. You probably wanted to write `if (line[0] == 'a')` instead – Elias Van Ootegem Feb 24 '16 at 14:11

3 Answers3

2

The strcmp function expects a char * for the first argument, but you're passing a char. Similarly with strcpy. This caused undefined behavior.

Your compiler should have given you a warning regarding this.

If what you're trying to do is see if a given character in the string is a, you would do it like this:

if (line[i] == 'a')
dbush
  • 205,898
  • 23
  • 218
  • 273
  • So can yoou explain to me why this also willnot work if(strcmp(*(line+i), "a") == 0){ – MFB Feb 24 '16 at 14:37
  • @MFB The expression `*(line+i)` is the same as `line[i]`, which is of type `char`, and therefore invalid as the first argument to `strcmp`. – dbush Feb 24 '16 at 14:52
2

In your code line is pointer to character(s). strcmp takes pointers to characters to compare but here

if(strcmp(line[0], "a") == 0)
//        ^^^^^^^^

you are passing character instead of a pointer to it.

Solution:

if(strcmp(line, "a") == 0)
// ...

or

if(line[0] == 'a')
// ...

Side note: there is no need to cast returned value of malloc. You should however check it for errors:

char *line;
line = malloc(maxLineLen);
if (line == NULL)
    perror("oh dear! Go on holidays.\n");
Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • if(strcmp(line[0], 'a') == 0) doesnot work also but if (line[i] == 'a') works – MFB Feb 24 '16 at 14:35
  • @MFB if(strcmp(line[0], 'a') == 0) doesn't work for sure – 4pie0 Feb 24 '16 at 14:41
  • can you explain to me why this also willnot work if(strcmp(*(line+i), "a") == 0){ – MFB Feb 24 '16 at 14:42
  • @MFB strcmp takes pointer to char, but *(line+i) is character itself, not a pointer to char, however if *(line+i) == 'a' is true then strcmp((line+i), "a") == 0 will work in your case as well. But you should use first comparison to compare single characters and strcmp to compare multicharacter strings. – 4pie0 Feb 24 '16 at 14:59
1

strcmp(line[0], ... is wrong. Use strcmp(line, ...).

You should #include <string.h>, so your compiler will show an error. Otherwise always compile with all warnings enabled and read the warnings your compiler shows you.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115