使用函数

时间:2015-10-15 22:19:55

标签: c struct initialization

这是在我的main.c

int main(){

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

这是我的路径。

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

这是我的路径。

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

有人可以解释为什么我的结构没有正确初始化。这也不是我的完整代码,但我已将问题缩小到这些部分。任何帮助都会很棒。感谢

2 个答案:

答案 0 :(得分:5)

您正在使用堆栈:

scope :within_weekday, -> (weekday) { where { (start_day <= weekday) & (end_day >= weekday) }
scope :within_time, -> (time) { where { (start_time <= time) & (end_time >= time) }

并传递一个指针:

Path Solution;

因此您无需使用PathInit(&Solution,size); 预留空间:

malloc

答案 1 :(得分:2)

正如@Alter Mann的回答中所提到的,问题是你搞砸了堆栈存储,这是未定义的行为。如果你想使用动态分配,你需要传递指针指针(和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);
相关问题