arrays - 没有正确打印数组的值(非常初学者编程)
问题描述
int main()
{
int arr1[25], i,n;
printf(" Input the number of elements to store in the array :");
scanf("%d",&n);
printf(" Input %d number of elements in the array :\n",n);
for(i=1;i<=n;i++)
{
printf(" element - %d : ",i);
scanf("%d",arr1);
}
printf(" The elements you entered are : \n");
for(i=1;i<=n;i++)
{
printf(" element - %d : %d \n", i, arr1[i]);
}
return 0;
}
代码打印的是随机数而不是数组中的值,这是为什么呢?
我刚刚开始学习,所以我试图了解在这种情况下出了什么问题。
我有其他练习,我可以使用相同的方法从数组中打印值:
解决方案
我知道你是初学者,所以我会尽量不要过多地谈论指针或任何东西。基本上,c 数组是指针,而 scanf 也需要指针。为了得到你想要的结果,下面的代码将起作用。我将尝试包括有用的评论。
编辑:为了澄清,你打印随机数的原因是因为C不会将数组值初始化为任何东西,所以它将是随机垃圾。您使用的 scanf 始终将值放在数组的开头: scanf("%d",arr1); 因此,数组的其余部分将只是随机垃圾。然而,下面发布的是一个完整的解决方案。
编辑 2:我忘记将第二个 for 循环更改为 <,而不是 <=。仅供参考,通常 for 循环是 i = 0 到 i < n,而不是 i = 1 到 i <= n。此外,还必须包含 stdlib.h。free() 用于防止此处的内存泄漏,尽管由于程序结束并不是真的需要,但我认为这段代码可能希望在多个地方使用。
int main(void)
{
int *arr1;
int i,n;
printf("Input the number of elements to store in the array : ");
scanf("%d",&n); /*We have now scanned in how long we want the array to be */
arr1 = malloc(sizeof(int) * n); /* Dynamically allocate memory for our array */
printf("Input %d number of elements in the array :\n",n);
for(i = 0; i < n; i++)
{
printf("element - %d : ",i);
scanf("%d", arr1 + i); /*We will store the int at the array with an offset of i
The reason we do this is because we want to store it at the correct index
and arr1 is a pointer */
}
printf(" The elements you entered are : \n");
for(i = 0; i < n; i++)
{
printf(" element - %d : %d \n", i, arr1[i]); /*We can still
dereference arr1 with [] */
}
free(arr1);
return 0;
}
推荐阅读
- reactjs - 无法运行 React Native Web 项目
- python - 为什么img.thumbnail调整会引发FileNotFoundError [Errno2] No such file directory?
- r - ggplot 中用于 3 轴图的轴变换
- c# - 在列表 C#(WPF 应用程序)中编辑文本块的内容
- python - Python中的随机鼠标移动和拖动时间
- ios - 是否可以快速将十六进制数据发送到 A2DP 蓝牙设备?
- python-3.x - 使用 pyscreenshot 截取正在运行的进程
- android - 为什么 Android Studio 3.2.1 中的新项目模板不使用 AndroidX 库?
- python - 拆分字母数字字符串
- google-apps-script - 谷歌电子表格中的图表文本响应