2013-02-08 77 views
2

我在以下種類的佈局中有一些代碼,我相信當我撥打addTopBotExampletopExample/botExample未被正確設置。我認爲這是由於頂級bot變量位於函數堆棧中,並在函數結束時被清除?我有一種感覺,也許我需要首先記憶,但我不知道如何去做這件事,即使它是正確的方法。設置結構體變量 - C

typedef struct Example Example; 
struct Example { 
    /* normal variables ...*/ 
    Example *topExample; 
    Example *botExample; 
}; 

.... 

void addTopBotExample(Example **example, int someVariable) { 
    Example top = createTopExample(int someVariable); //(createTopExample returns a 
                 //type Example based on some input) 
    Example bot = createBotExample(int someVariable); 
    (*example)->topExample = ⊤ 
    (*example)->botExample = ⊥ 
    return; 
} 

回答

2

如果createTopExample不分配內存,這會導致問題,它被稱爲不止一次的時刻。重寫createTopExamplecreateBotExample以使用malloc並返回Example*。事情是這樣的:

Example* createTopExample(stuff) 
{ 
    Example *example = malloc(sizeof(Example)); 
    // ... stuff you do 
    return example; 
} 

然後你addTopBotExample應該是這樣的:

void addTopBotExample(Example **example, int someVariable) { 
    if ((*example)->topExample) 
     free((*example)->topExample) 
    if ((*example)->botExample) 
     free((*example)->botExample) 
    (*example)->topExample = createTopExample(int someVariable); 
    (*example)->botExample = createBotExample(int someVariable); 
    return; 
} 

注意,這addTopBotExamplefree分配的內存再次調用malloc之前,但你的程序結束之前,你需要調用free在任何揮之不去的Example使用此功能addTopBotExample功能:

free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.topExample); 
free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.botExample); 
+0

由於這確實是這個問題。 – 2013-02-08 23:54:18

0

你已經擁有了一切。分配ExamplecreateTopExamplecreateTopExample

Example *createTopExample(int someVariable) 
{ 
    Example *x = malloc(sizeof(Example)); 
    /* initialize x */ 
    return x; 
} 

addTopBotExample

void addTopBotExample(Example *example, int someVariable) { 
    Example *top = createTopExample(int someVariable); //(createTopExample returns a 
                 //type Example based on some input) 
    Example *bot = createBotExample(int someVariable); 
    example->topExample = top; 
    example->botExample = bot; 
    return; 
} 
0

Ooooo,這很糟糕。 addTopBotExample()函數中的「Example top」表達式在堆棧中分配了該對象。它將在退出該功能後被刪除。 (同爲「示例機器人」下一行)這樣的事會工作得更好:

void addTopBotExample(Example **example, int someVariable) { 
    Example *top = createTopExample(someVariable); // NOTE THE * 
    Example *bot = createBotExample(someVariable); // NOTE THE * 

    (*example)->topExample = top; // NOT &top !! 
    (*example)->botExample = bot; // NOT &bot !! 
    return; 
} 

而且你會想要寫createTopExample和createBotExample讓他們返回指針:

#include <stdlib.h> // For malloc! 
Example *createTopExample(stuff) // Note *. It's returning a pointer. 
{ 
    Example *example = malloc(sizeof(Example)); // Allocate on the HEAP. Lives after this function call. 

    // Fill in the fields of example. 
    example->field1 = 25; // Note the "->": you're dereferencing a pointer. 
    example->title = "Example title"; 

    return example; 
}