gpt4 book ai didi

C- 数组末尾的神秘值

转载 作者:行者123 更新时间:2023-11-30 19:33:55 25 4
gpt4 key购买 nike

我试图在数组末尾插入一个整数。然而,当我尝试执行代码时,随机值(47)出现在最后一个位置。即使我更改要插入的值,47 也不会更改。 Output is this.

谁能告诉我为什么是47?而且是垃圾值吗?我的代码如下:-

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
int upper=6;
int a[upper];
int i;
for(i=0;i<upper;i++)
{
scanf("%d",&a[i]);
}
printf("The array before insertion is \n");
for(i=0;i<upper;i++)
{
printf("%d \n",a[i]);
}
printf("\n The array after insertion is \n");
upper=upper+1;
a[upper]=66;
for(i=0;i<upper;i++)
{
printf("%d \n",a[i]);
}
return 0;
}

最佳答案

您声明了一个大小为 upper (6) 的数组,但在这里:

a[upper]=66;

您尝试访问数组的第 8 个位置(因为您之前访问过 upper= upper + 1) - 一个您不拥有的位置。你正在做的是 UB,因此它可以打印 47 或者其他任何事情都可能发生

关于C- 数组末尾的神秘值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com