2015-10-15 61 views
0

這是我的main.c初始化結構使用功能

int main(){ 

int size = 5; 
Path Solution; 
PathInit(&Solution,size); 
printf("Size: %d\n",Solution.size); 
printf("top: %d", Solution.top); 
} 

這是我path.h

typedef struct{ 
int size; 
int top; 
int *item; 
}Path; 

這是我path.c

void PathInit(Path *P, int vsize){ 
P = (Path *)malloc(sizeof(Path)); 
P->size = vsize; 
P->item = (int *)malloc(sizeof(int)*vsize); 
P->top = -1; 

}

期望的輸出是

Size: 5 
top: -1 

但是輸出沿着

Size: 3412832 
top: 0 

線有人能解釋爲什麼我的結構不正確初始化的東西。此外,這不是我的完整代碼,但是將問題縮小到這些部分。任何幫助都會很棒。由於

回答

5

您正在使用的堆棧:

Path Solution; 

並將指針傳遞:

PathInit(&Solution,size); 

,所以你不需要用malloc預留空間:

void PathInit(Path *P, int vsize){ 
    P = (Path *)malloc(sizeof(Path)); /* Remove this line */ 
+1

非常感謝,這真的幫助:d –

+0

歡迎您;) –

2

由於在@Alter Mann's的回答中提到,問題是你搞不清堆棧存儲,這是未定義的行爲。如果你要使用動態分配的,你需要傳遞一個指向指針(和BTW there is no need to cast the result of malloc in C),這樣你就可以修改它在你的功能,如:

#include <stdio.h> 
#include <stdlib.h> 

typedef struct { 
    int size; 
    int top; 
    int *item; 
} Path; 

void PathInit(Path **P, int vsize) { // pass pointer to pointer so we can modify it 
    *P = malloc(sizeof(Path)); // No need (and not recommended) to cast malloc in C 
    (*P)->size = vsize; 
    (*P)->item = malloc(sizeof(int) * vsize); 
    (*P)->top = -1; 
} 

int main() { 

    int size = 5; 
    Path* Solution; // this is now a pointer 
    PathInit(&Solution, size); 
    printf("Size: %d\n", Solution->size); 
    printf("top: %d", Solution->top); 
    free(Solution->item); 
    free(Solution); 
} 

否則,你需要從返回指針你功能:

Path* PathInit(int vsize) { 
    Path* tmp = malloc(sizeof(Path)); 
    tmp->size = vsize; 
    tmp->item = malloc(sizeof(int) * vsize); 
    tmp->top = -1; 
    return tmp; 
} 

,並調用它像

Path* Solution; 
Solution = PathInit(size);