我制作了一个可以容纳2个称为“ arr”的整数的数组,但是当我要求范围之外的值而不是收到错误时,我得到了一个实际值。实际上,当我在索引3的“ arr”索引中设置一个值,然后要求程序在该位置打印该值时,不仅我没有收到错误,而且程序还提供了我在那里设置的实际值。但是我从来没有为“ arr”重新分配内存空间,所以这怎么工作?
代码:
#include <stdio.h>
#include <stdlib.h>
int main(){
int* arr = malloc(2 * sizeof(int));
arr[0]=5;
arr[1]=6;
arr[3] = 70; //this should be a segfault, right?
while(1){
int index;
printf("\n\nWhich number do you want?");
scanf("%d", &index);
int val = arr[index];
printf("here is your number: %d", val);
}
}
输出:
Which number do you want?0
here is your number: 5
Which number do you want?1
here is your number: 6
Which number do you want?2
here is your number: 0
Which number do you want?3
here is your number: 70
Which number do you want?4
here is your number: 0