0

Hi their, I am learning C and a bit stuck on pointer to strings(I now they dont really exist in c but yeah) which i saw in the absolute guide to c programmig book. I am wondering why this code below doesnt work? If you could answer this question it would be really helpful thanks.

#include <stdio.h>
main(){
char * list[4] = {"tom", "john", "albert", "lily"};
char answer[10];
printf("enter your name");
scanf("%s", answer);
int i;
for(i = 0; i <4 ; i++){
    if(answer == list[i]){
        printf("found");
    }
    else{
        printf("not found");
    }
}
}
2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by Lucaci Andrew
0

here, this should fix it:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char * list[4] = {"tom", "john", "albert", "lily"};
    char answer[10];
    printf("enter your name");
    scanf("%9s", answer);
    int i, check=0;
    for(i = 0; i <4 ; i++){
        if(strcmp(answer, list[i])==0){
            printf("Found.\n");
            check++;
            break;
        }
    }
    if (!check) printf("Not found.\n");
    return (0);
    getchar();
}

perhaps the

if(answer == list[i])

condition is wrong. Plus, let's say that the condition works fine, then it will print 4 times, either if your name was found or not. So, if you do find if, you have to break the loop, end putting the else in the for makes it to print every time the condition of if is not true.
Perhaps this cods is not working because your main function has no type, you just put there main(){}. You see it has to have the syntax like this:

int main(){
    //do stuff
    return(0);
}

Edited by Lucaci Andrew

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.