我想在主要功能中实例化此“ JobSequence”结构。为此,我创建了一个new_JobSequence()
函数,该函数分配内存并为结构的所有字段提供适当的值。在此函数中,一切都根据我的调试器正确完成。但是一旦回到主函数int cost
就被设置为任意值baseInstance = 0x0
和list = 0x1
。 jobSequence
之前和之后的new_JobSequence()
地址是不变的,并且与函数内部使用的地址相同。
这是结构的声明,函数的代码和main的代码:
typedef struct JobSequence{
Instance* baseInstance;
List* sequence;
int cost;
}JobSequence;
void new_JobSequence(Instance* baseInstance, JobSequence* jobSequence){
jobSequence = malloc(sizeof(JobSequence));
jobSequence->baseInstance = baseInstance;
jobSequence->cost = 0;
list_new(&jobSequence->sequence);
}
int main() {
int** P = baseInstance();
Instance instance;
makeInstanceFromBin(P,10,10,4,&instance);
printInstance(&instance);
JobSequence jobSequence;
setbuf(stdout, 0);
printf("address : %p\n",&jobSequence);
new_JobSequence(&instance,&jobSequence);
setbuf(stdout, 0);
printf("address : %p\n",&jobSequence);
Do other stuff (crashes because I try to access the elements of jobSequence which have 0x1 and 0x0 addresses).
}
所以我确实尝试了很多东西,但我真的不知道这里发生了什么...
谢谢您的帮助。
答案 0 :(得分:1)
写作时
JobSequence jobSequence;
您要求编译器在堆栈上创建类型为JobSequence
的变量。
所以您不必自己保留内存。
您在调试器中遇到的问题是jobSequence
函数未修改main
函数中的new_JobSequence
。
您可以通过一些调试痕迹看到它:
void new_JobSequence(Instance* baseInstance, JobSequence* jobSequence){
printf("start of %s: js is %p\n", __FUNCTION__, jobSequence);
jobSequence = malloc(sizeof(JobSequence));
printf("after malloc, js is %p\n", jobSequence);
jobSequence->baseInstance = baseInstance;
jobSequence->cost = 0;
list_new(&jobSequence->sequence);
}
因此,要使您的函数在main
中创建的变量上起作用,您必须编写类似以下内容的
void new_JobSequence(Instance* baseInstance, JobSequence* jobSequence)
{
jobSequence->baseInstance = baseInstance;
jobSequence->cost = 0;
list_new(&(jobSequence->sequence));
}
...
int main(void)
{
/* ... */
JobSequence jobSequence;
new_JobSequence(..., &jobSequence);
}
如果要在堆上为结构分配内存,则必须遵循以下方法:
JobSequence *new_JobSequence(Instance* baseInstance){
JobSequence *js= malloc(sizeof *js);
js->baseInstance = baseInstance;
js->cost = 0;
list_new(&(js->sequence));
return js;
}
...
int main(void)
{
/* ... */
JobSequence *jobSequence = new_JobSequence(...);
}
答案 1 :(得分:0)
您已经在主函数中分配了实例。因此,您实际上在new_JobSequence()
内部所做的只是在堆中分配一些内存,对其进行初始化,并且在从该函数退出之前从不返回任何内容。如果要保持这种操作流程,则需要在函数中传递一个双指针(并在主函数(即JobSequence *pJobSequence = NULL
中仅分配一个指针))。