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