2015-10-19 18 views
1

當我運行此代碼時,它會運行,直到我到達主函數中的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]); 
    } 
} 
+2

C是按價值傳遞的。更改函數中的參數不會影響調用方中的參數。 – EOF

+0

...但是,如果您將參數的地址作爲指針傳遞,則可以更改此指針定位的值。 – peterh

+1

@peterh:...或者你可以做出理智的事情,並返回一個指針。 – EOF

回答

1

這個錯誤與你的代碼在不同的文件中沒有任何關係。

當您撥打VectorRead()時,您正在傳遞一個指針值。在該功能中,您將本地V設置爲對malloc()的調用的返回值。當地V沒有辦法返回給調用者。

您將需要做一些事情來將新分配的值V返回給調用者。改變你的函數返回一個Vector *(而不是一個參數)將是一個好方法。

1

當您調用VectorRead()時,您當地的Vector,V未被修改。嘗試在你的函數,而不是接受Vector **

void VectorRead(Vector **V) 

並修改相應的功能。

或者,因爲你的函數沒有返回值,並作爲@EOF在評論中指出,它可能是一個更好的主意帶一個參數,並簡單地返回Vector *

Vector *VectorRead(void) 
+2

爲什麼每個人都想讓人們使用多重間接?只是'返回'該死的指針! – EOF

+0

這是一個選項。但是,在某些情況下它可能更安全,而不是簡單地返回,或者如果需要不同的返回值等等。 – owacoder

+0

鑑於OP的函數是'void',將其更改爲返回'Vector *'似乎沒有非常困難。 – EOF