There are multiple problems:
C strings cannot be compared with ==
as you do. You just compare the pointers, not the contents of the arrays. You must include <string.h>
and use:
if (strcmp(s[i].name, s[j].name) == 0) {
/* duplicate name */
}
Also note that gets()
must not be used as it may cause undefined behavior if the input is too long. As a matter of fact, attackers may take advantage of this flaw to execute arbitrary code. Use fgets()
or scanf("%19s", s[i].name)
.
Why do you define the students
array with 10 entries and only use 3 in the rest of the main()
function?
Here is a modified version:
#include <stdio.h>
#include <string.h>
struct student {
char name[20];
};
int main() {
struct student s[10];
int n, i, j, count;
for (n = 0; n < 10; n++) {
printf("Enter student name: ");
if (scanf("%19s%*[^\n]", s[n].name) < 1)
break;
}
count = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(s[i].name, s[j].name) == 0) {
count++;
}
}
}
printf("\n%d students have same name\n\n", count);
return 0;
}
EDIT: Your counting method is incorrect for more than 3 entries: if the 4 students have the same name, count
will be incremented for pairs 0,1
, 0,2
, 0,3
, 1,2
, 1,3
and 2,3
hence 6 students with the same name (!).
Here is a corrected version that does not use strcmp()
either:
#include <stdio.h>
struct student {
char name[20];
};
int same_string(const char *s1, const char *s2) {
while (*s1 == *s2) {
if (*s1 == '\0')
return 1;
s1++;
s2++;
}
return 0;
}
int main() {
struct student s[10];
int n, i, j, count;
for (n = 0; n < 10; n++) {
printf("Enter student name: ");
if (scanf("%19s%*[^\n]", s[n].name) < 1)
break;
}
count = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i != j && same_string(s[i].name, s[j].name)) {
count++;
break;
}
}
}
printf("\n%d students have same name\n\n", count);
return 0;
}