C中多次循环失败后出现段错误
我正在做一个练习,创建一个数组并用整数填充元素。我首先将数组的长度输入到 malloc 中作为大小。然后,我在 for 循环中扫描数组中每个点的元素。
这是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int scaning(int ** array){
int size;
scanf("%d", &size);
*array = malloc(sizeof(int)*size);
//printf("%d\n", size);
for (int i=0; i<=size; i++){
int num;
scanf("%d", &num);
*array[i] = num;
}
return size;
}
int main(){
int * array;
int zero;
zero = scaning(&array);
//printf("%d\n", zero);
printf("LOOPS\n");
for (int i=0; i<= zero; i++){
printf("%d\n", array[i]);
}
return 0;
}
在我输入元素来填充数组两次后,我得到了一个段错误。我通常输入 5 个数组的大小,输入 2 个数字,然后它就会崩溃。不知道我哪里出错了。有什么想法吗?
I am doing an exercise where I create an array and populate the elements with integers. I first input the length of the array to malloc for the size. Then, I scan the elements of each point in the array in a for loop.
Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int scaning(int ** array){
int size;
scanf("%d", &size);
*array = malloc(sizeof(int)*size);
//printf("%d\n", size);
for (int i=0; i<=size; i++){
int num;
scanf("%d", &num);
*array[i] = num;
}
return size;
}
int main(){
int * array;
int zero;
zero = scaning(&array);
//printf("%d\n", zero);
printf("LOOPS\n");
for (int i=0; i<= zero; i++){
printf("%d\n", array[i]);
}
return 0;
}
After I input the elements to populate the array twice I get a seg fault. I usually put in size for the array of 5, get to input 2 numbers and then it crashes. Not sure where I went wrong. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的程序中的 for 循环
具有无效条件
i <= size
。索引的有效范围是[0, size)
。您需要使用条件
i
i
i
i
i
i
i
i <大小。
另一个问题与运算符优先级有关。
相反
,相当于
您需要编写
或至少
可以按以下方式定义函数
相应的变量
zero
(为什么命名为“zero”?)也必须具有类型大小_t。
请注意,您应该释放 main 中分配的数组,例如
The for loops in your program like this
have the invalid condition
i <= size
. The valid range of indices is[0, size)
.You need to use the condition
i < size
.Another problem is related to the operator precedence.
Instead of
that is equivalent to
you need to write
or at least
The function can be defined the following way
Correspondingly the variable
zero
(why is it named "zero"?) also must have the typesize_t
.Pay attention to that you should free the allocated array in main like
由于
size
是数组中整数的数量,因此您不想循环直到i<=size
。您想要循环直到 ii
i
i
i
i
i
i
i
i仅大小。请记住,数组中的第一项的索引为零,因此最后一项的索引是大小减一。如果循环直到并将 size 包含为索引,则会导致段错误。
Since
size
is the number of integers in your array, you don't want to loop untili<=size
. You want to loop untili < size
only. Remember that the first item in your array has index zero, so the index of the last item is size minus one. If you loop until and including size as index, that will cause a seg fault.