gpt4 book ai didi

谁能告诉我为什么在这个 C 代码中出现段错误?

转载 作者:行者123 更新时间:2023-11-30 17:09:11 25 4
gpt4 key购买 nike

嗨,我刚刚开始用 C 语言编程,我正在制作一个数组计数器,但当我尝试运行此命令时,出现段错误:

//function to calculate the length of an array
int arr_length(char arr[]) {
int i = 0;

while(arr[i] != "\0") {
i++;
}

return i;
}

最佳答案

while(arr[i] != "\0") {
i++;
}

相当于:

char const* str = "\0";
while(arr[i] != p) {
i++;
}

您正在将 charchar* 进行比较。大多数时候它的计算结果为false。结果,您最终访问的 arr 超出了有效限制,从而导致未定义的行为。在您的情况下,这表现为段错误。

您需要使用:

while(arr[i] != '\0') {  // Compare with the null character
i++;
}

关于谁能告诉我为什么在这个 C 代码中出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com