You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Visual Studio 2022编译的C代码正常,GCC 8.2编译却异常?

最长公共前缀函数跨编译器结果不一致问题

我是C语言新手,正在刷LeetCode题。写了个返回字符串数组最长公共前缀的函数,大部分测试用例都正常,但测试数组{"aaa", "aa", "aaa"}时,Visual Studio 2022输出正确结果"aa",GCC 8.2却输出"aaa",搞不懂原因。

原代码

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

char* longestCommonPrefix(char** strs, int strsSize) {

    char* result = calloc(200, sizeof(char));
    if (result == NULL) return NULL;
    size_t result_length = strlen(strs[0]);
    memcpy(result, strs[0], result_length);
    char* result_end = result + result_length + 1;


    for (size_t i = 1; i < strsSize; ++i) {
        char* ptr_res = result;
        char* ptr_cur = strs[i];

        while (*ptr_res == *ptr_cur && *ptr_res > '\0' && *ptr_cur > '\0') {
            ++ptr_res;
            ++ptr_cur;
        }

        result_end = ptr_res;
    }
    *result_end = '\0';
    return result;
}


int main(int argc, char* argv[]) {
    char* a[3];
    a[0] = "aaa";
    a[1] = "aa";
    a[2] = "aaa";

    char* b = longestCommonPrefix(a, 2);
    printf(b);
    free(b);
}

感谢@Chris、@EricPostpischil、@VladFromMoscow指出问题,学到了很多。采用@EricPostpischil的方案修改后代码可以正常运行,以下是提交到LeetCode的可用代码:

修正后代码

char* longestCommonPrefix(char** strs, int strsSize) {

    char* result = calloc(200, sizeof(char));
    if (result == NULL) return NULL;
    size_t result_length = strlen(strs[0]);
    memcpy(result, strs[0], result_length);
    char* result_end = result + result_length;


    for (size_t i = 1; i < strsSize; ++i) {
        char* ptr_res = result;
        char* ptr_cur = strs[i];

        while (*ptr_res == *ptr_cur && ptr_res < result_end) {
            ++ptr_res;
            ++ptr_cur;
        }

        result_end = ptr_res;
    }
    *result_end = '\0';
    return result;
}

内容的提问来源于stack exchange,提问作者OldCrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:12:39