【发布时间】:2016-08-21 12:14:03
【问题描述】:
我正在编写处理字符串和整数数组的代码。
这个编译运行正常,但是数组的内容被修改了。
代码给出了最大数字的主要结果。 但是,在排序过程之后,我显示了数组的内容,其中一个元素被修改为 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。当您将最大的数字交换到此处,即在您的数组之外,您将碰巧为零的垃圾交换到您的数组中。
-
使用调试器单步调试代码以了解实际情况。
-
是的,谢谢,我添加了 printf("OK");在循环中查看问题出在哪里。它实际上是关于循环计数器的,它现在可以工作了。