當我運行此代碼時,它會運行,直到我到達主函數中的printf語句時,即當出現分段錯誤錯誤時。所以它會像「輸入你想要的數字」那樣運行3「在數組中輸入數字」1 2 3 array [0] = 1 array [1] = 2 array [2] = 3分段錯誤。你能告訴我爲什麼即時通訊出現這個錯誤,以及如何解決它?謝謝C:從另一個文件運行功能時的分段錯誤
//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是按價值傳遞的。更改函數中的參數不會影響調用方中的參數。 – EOF
...但是,如果您將參數的地址作爲指針傳遞,則可以更改此指針定位的值。 – peterh
@peterh:...或者你可以做出理智的事情,並返回一個指針。 – EOF