使用 = 运算符时字符串数组出现意外结果

Getting unexpected results for array of strings when using = operator

在下面的代码中,我得到了意想不到的结果。在第一次迭代期间,s[0] 被打印为第一个元素。但是在剩余的迭代中,打印了 0。使用 = 运算符而不是 strcpy 是错误的吗?我尝试使用 strcpy 但它会导致分段错误。为什么打印出错误的值?

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] 与空字符串相等。
if 条件中的 0 表示 false,因此不执行 if 块。我相信你希望它被执行。所以你应该做

if (strcmp(final[end], "") == 0)

同样适用于else if语句。