【发布时间】:2015-10-19 02:01:47
【问题描述】:
当我运行这段代码时,它会一直运行,直到我到达我的 main 函数中的 printf 语句,这就是我得到分段错误错误的时候。所以它会像“输入你想要的数字”3“输入数组中的数字”一样运行 1 2 3 array[0] = 1 array[1] = 2 array[2] = 3 分段错误。你们能告诉我为什么我会收到这个错误以及如何解决它吗?谢谢你
//pathfinder.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Vector.h"
int main()
{
Vector *V;
VectorRead(V);
printf("%d", V->item[0]);
return 0;
}
//Vector.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct{
int *item;
int size;
} Vector;
void VectorRead(Vector *V) ;
void VectorRead(Vector *V)
{
int N;
printf("Enter how many numbers you want?\n");
scanf("%d", &N);
V = (Vector *)malloc(sizeof(Vector *) * N);
V->size = N;
V->item = (int *)malloc(sizeof(int *) * V->size);
printf("Enter the numbers that you want in your array\n");
int i = 0;
while(i < V->size && scanf("%d", &(V->item[i++])) == 1);
int j;
for(j = 0; j< V->size; j++){
printf("array[%d]=%d\n", j, V->item[j]);
}
}
【问题讨论】:
-
C 是按值传递。更改函数中的参数不会影响调用者中的参数。
-
...但是如果将参数的地址作为指针传递,则可以更改此指针所针对的值。
-
@peterh: ...或者你可以做理智的事情和
return一个指针。 -
@EOF 顺便说一句,C 的美妙之处在于它的肮脏。 :-) 是的,C 主要是按值传递,但数组是按地址传递的。 C中没有规则,没有例外:-)嗯,它是在BCPL之后的下一步命名的,但实际上它缩写为我_C_haos :-)
-
您在两次 malloc 调用中都分配了错误的字节数。这可以通过使用模式
p = malloc( N * sizeof *p );来避免
标签: c