我有一个随机数生成器将数字输入数组,但是当我打印出表格时,最后一行总是超出我在以下函数中定义的边界的一组值:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int temp[22];
int n;
for(n=0; n<23; n++){
temp[n] = rand()%(100 + 1 - 60) + 60;
printf("%d , %d \n", n, temp[n]);
}
return 0;
我以前创造过这种性质的东西,但现在它在起作用,我只是不知道在哪里。
最佳答案
您正在访问边界之外的数组,这是未定义的行为。
改为使用sizeof
运算符来避免此类问题:
for(n = 0; n < sizeof temp/sizeof temp[0]; n++)
但是请注意,如果 temp
是一个 malloc 指针 (int *temp = malloc(23 * sizeof *temp);
) 那么 sizeof
不会工作。
关于c - 访问数组中的最后一项时索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43006159/