#include <stdio.h>
typedef struct Name {
char Name[10];
}Name;
A(Name a) {
Name NameList[16] = {"", "Holly", "Zia", "Brandon","Jerry","Tom","Katie","Klein","Sophie","Brian","Mary","Ben","Annie","Percy","Zoe","Zack"};
for (int i = 0; i <= 15; i ) {
if (a = NameList[i]) {
for (int k = i; k <= 15; k ) {
printf(NameList k);
}
break;
}
else {
continue;
}
}
}
I'm getting problems with if (a = NameList[i]) this part.. compiler tells me that I need pointers, but I'm not sure where I have to put them.. help?
CodePudding user response:
a = NameList[i]
is an assignment, not comparison. In general you need to use==
for comparison.- In C a string is an array of chars, zero terminated. In order to compare strings in C you need to use
strcmp
. Note that it returns 0 if the strings are equal. a
is not actually a string, but contains one.a.Name
is a string. Same applies toNameList[i]
.- A struct should not contain a member with the same name as the struct itself (even if your compiler accepts it, it is error-prone). You should rename the member
Name
(e.g. todata
).
Therefore after modifying the struct definition, you should change your if
to:
if (strcmp(a.data, NameList[i].data) == 0)
CodePudding user response:
First of all the statement if (a = NameList[i]) {bla..} does not do what you think it does. It first executes the command a = NameList[i] and then evaluates if (a != 0) in which case the commands inside the if statement will be executed.
That's a mistake everyone has made at some point ,even more experienced programmers might make this mistake from time to time.
Now I see you are trying to compare two strings ,in C we do this using the function strcmp(a ,b) .If strcmp returns 0 ,the two strings you gave it are equal.
Another mistake you made ,is that you are comparing two structs instead of their contents. You have to use if(!strcmp(a.Name ,NameList[i].Name)) instead.
So your main issue is that you are comparing structs not their contents.