In the below code I am getting unexpected result. During first iteration s[0] is getting printed as the first element. But during the remaining iteration, 0 is getting printed. Is it wrong to use = operator instead of strcpy? I tried using strcpy but it results in segmentation fault. Why is wrong value getting printed?
int main() {
int n, i;
scanf("%d", &n);
int c, j;
char* s[n];
char* ch = (char*)malloc(100);
for (i = 0; i < n; i++) {
scanf("%s", ch);
s[i] = strdup(ch);
}
char* final[n];
int count[n];
for (i = 0; i < n; i++) {
final[i] = "";
count[i] = 0;
}
int end;
for (i = 0; i < n; i++) {
end = 0;
while (1) {
printf("%s\n", s[0]);
if (strcmp(final[end], "")) {
count[end]++;
final[end] = s[i];
// printf("%s\n",final[end]);
end++;
break;
}
else if (strcmp(final[end], s[i])) {
final[end] = s[i];
sprintf(final[end], "%d", count[end]);
count[end]++;
end++;
break;
}
end++;
}
}
for (i = 0; i < n; i++) {
// printf("%s\n",final[i]);
}
return 1;
}
if (strcmp(final[end], ""))
strcmp
returns 0
if final[end]
compares equally to the empty string.
A 0
in the if
condition means false
, so the if-block is not executed. I believe you want it executed. So you should do
if (strcmp(final[end], "") == 0)
The same applies to the else if
statement.