2015-10-15 65 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);