c - 访问数组中的最后一项时索引超出范围

标签 c arrays loops

我有一个随机数生成器将数字输入数组,但是当我打印出表格时,最后一行总是超出我在以下函数中定义的边界的一组值:

#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/

相关文章:

java - 将我的素数生成器存储到数组中

c - C 程序错误 ‘struct client_thread *’ 但参数类型为 ‘int’

c - 使用 scanf 的段错误

c - 如何将动态数字字符串转换为动态整数数组

c - 如何继续使用 malloc?

python - 无法使用 Python 循环分页 API 响应

c - 无法正常写入文件

arrays - 迭代哈希以检索与数组匹配的值

php - 如何在 PHP/CakePHP 中将关联数组转换为一组 HTML 表格行?

JavaScript setInterval 问题