我正在处理字符串和整数数组的代码。int数组排序修改数组内容
这个编译并运行正常,但数组的内容被修改。
该代码给出了最大数目的主要结果。 但是,排序过程后,我显示数组的内容,其中一个元素被修改为0. 那么,这是什么原因?
问候,
#include<stdio.h>
#include<string.h>
#include<stdint.h>
int main()
{
static uint8_t arr2[]={5,100,-2,75,42},cr=0,ps=1,temp=0;
uint8_t i;
for (i=0;i<sizeof(arr2);i++)
{
printf("1stloop[%d]\n",i);
if (arr2[cr]>arr2[ps])
{
printf("before change1 cr %d ps %d\n",arr2[cr],arr2[ps]);
temp=arr2[cr];
arr2[cr]=arr2[ps];
arr2[ps]=temp;
printf("change1 cr %d ps %d\n\n",arr2[cr],arr2[ps]);
if (arr2[cr-1]>arr2[ps-1])
{
printf("before change2 cr %d ps %d\n",arr2[cr-1],arr2[ps-1]);
temp=arr2[cr-1];
arr2[cr-1]=arr2[ps-1];
arr2[ps-1]=temp;
printf("change2 cr %d ps %d\n\n",arr2[cr-1],arr2[ps-1]);
}
}
cr++; ps++;
}
for (i=0;i<sizeof(arr2);i++)
{
printf("contents %d \n",arr2[i]);
}
printf("\nLargest No. in arr2 of arr2 is %d \n",(arr2[sizeof(arr2)]));
return 0;
}
当cr == 0时,你正在使用arr2 [cr-1]。索引-1在你的数组之外。当ps == sizeof(arr2)== 5时,您还使用arr2 [ps]。索引5也在您的数组之外。您最后打印的最大数字来自索引5 - 在阵列之外。当你将最大的数字交换到这里,即在你的数组之外时,你将发生零的垃圾交换到你的数组中。 –
通过使用调试器的代码来了解真正发生的事情。 – alk
是的,谢谢你,我添加printf(“OK”);在循环中查看问题出在哪里。它实际上是关于循环计数器,现在它可以工作。 –