如何解决不能正确打印数组的值非常初学者编程
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",arr1[i]);
}
return 0;
}
代码正在打印随机数而不是数组内部的值,为什么?
我刚刚开始学习,所以我试图了解这种情况下出了什么问题。
我还有其他练习,可以使用相同的方法从数组中打印值:
解决方法
我了解您是一个初学者,所以我将尽量不过多谈论指针或其他任何内容。基本上,c数组是指针,scanf也期望指针。为了获得所需的结果,以下代码将起作用。我将尝试添加有用的评论。
编辑:澄清一下,您这样做时要打印随机数的原因是因为C不会将数组值初始化为任何值,因此它将是随机垃圾。您使用的scanf总是将值放在数组的开头:scanf(“%d”,arr1);因此,数组的其余部分将仅保留为随机垃圾。但是,下面发布的是完整的解决方案。
编辑2:我忘记将第二个for循环更改为
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。