gpt4 book ai didi

c - 为什么 2 在 Codeblocks 上不小于 10?

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:48 26 4
gpt4 key购买 nike

我刚刚用简单的代码准备了期末考试;当我尝试对字符串进行排序时,我遇到了烦人的错误。为什么 2 在我的 CodeBlocks IDE 上不小于 10 但在 real 和 onlinegdb.com 上小于 10?

这是烦人的代码:

#include <string.h>
#include <stdio.h>
#define STR_SIZ 20

int main()
{
char strArr[][STR_SIZ] = {"abc", "hdas", "sdfasf", "kakldf", "caksl", "casd", "keam", "cznjcx", "mnxzv", "jkalkds"};
char minStr[STR_SIZ];
strcpy(minStr, strArr[0]);
int N = sizeof(strArr)/sizeof(minStr);
// int N = 10;
for(int x = 0; x < N-1; x++)
{
printf("%d", x);
strcpy(minStr,strArr[x]);
int j;
for(j=1+x; j < 10; j++)
{
printf("%4d\n", j);
int cmp = strcmp(strArr[j], minStr);
if(cmp < 0)
strcpy(minStr,strArr[j]);
}
char temp[STR_SIZ];
strcpy(temp,strArr[x]);
strcpy(strArr[x], minStr);
strcpy(strArr[j], temp);
}


return 0;
}

onlinegdb.com 上的输出:

0   1
2
3
4
5
6
7
8
9
1 2
3
4
5
6
7
8
9
2 3
4
5
6
7
8
9
3 4
5
6
7
8
9
4 5
6
7
8
9
5 6
7
8
9
6 7
8
9
7 8
9
8 9

CodeBlocks 上的输出:

0   1
2
3
4
5
6
7
8
9
1 2
3
4
5
6
7
8
9
2

PS:我早上刚用过Codeblock,执行起来没问题。

最佳答案

strArr 有 10 个元素。在循环结束时,调用 strcpy(strArr[j], temp);。这将写入 strArr[10],这是越界的,将覆盖一些未知的内存。之后任何事情都可能发生。

将字符串复制到 minStr 时,应保存 j 值。

关于c - 为什么 2 在 Codeblocks 上不小于 10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299788/

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