2012-10-09 59 views
2

下面是一些psudo,但我試圖做到這一點。問題與書面一樣,它返回一個空白指針。如何malloc裏面的函數和C返回指針?

int testFunction(char *t) { 
    int size = 100; 
    t = malloc(100 + 1); 
    t = <do a bunch of stuff to assign a value>; 
    return size; 
} 

int runIt() { 
    char *str = 0; 
    int str_size = 0; 
    str_size = testFunction(str); 
    <at this point, str is blank and unmodified, what's wrong?> 
    free(str); 
    return 0; 
} 

這工作得很好,如果我有一個預定義的大小,如焦炭海峽[100] =「」,我不嘗試的malloc或免費的內存後記。我需要能夠使尺寸動態。

我也試過這個,但似乎碰到了一個損壞的指針莫名其妙。

int testFunction(char **t) { 
    int size = 100; 
    t = malloc(100 + 1); 
    t = <do a bunch of stuff to assign a value>; 
    return size; 
} 

int runIt() { 
    char *str = 0; 
    int str_size = 0; 
    str_size = testFunction(&str); 
    <at this point, str is blank and unmodified, what's wrong?> 
    free(str); 
    return 0; 
} 

謝謝!

回答

4

你快到了與第二個例子,但改變

int testFunction(char **t) { 
    ... 
    t = malloc(100 + 1); 

int testFunction(char **t) { 
    ... 
    *t = malloc(100 + 1); 

,你傳遞一個char**問題的關鍵是,一個指向指針,所以你想分配malloc指向(指針)的那些點。

7

您的測試功能有點落後。大小應該是輸入。分配的指針應該是輸出

char* testFunction(int size) { 
    char* p = malloc(size); 
    <do a bunch of stuff to assign a value>; 
    return p; 
} 

int runIt() { 
    char *str = 0; 
    int str_size = 100; 
    str = testFunction(str_size); 
    <do something> 
    free(str); 
    return 0; 
} 

編輯

根據註釋,使大小的輸出了。

char* testFunction(int *size) { 
    *size = <compute size>; 
    char* p = malloc(size); 
    <do a bunch of stuff to assign a value>; 
    return p; 
} 

int runIt() { 
    char *str = 0; 
    int str_size; 
    str = testFunction(&str_size); 
    <do something> 
    free(str); 
    return 0; 
} 
+0

+1看起來這是他真正想要做的。 – AusCBloke

+0

這將是一個很好的選擇,除非在我的代碼中,變量「size」必須在testFunction中確定。標記的答案是針對我的問題的解決方案。謝謝。 – Fmstrat

0

我也在學習C++。我有一個相同的問題。因此,在向工作人員講C++ pro之後,他建議我做這樣的事情。

int method(char* p) {     
    if (p) { 
    strcpy(p, "I like c++"); 
    } 
    return strlen("I like c++"); 
} 

int main() 
{ 
     char* par = NULL; 
     int len = method(par); 

     if (len > 0) { 
      par = (char*)malloc(len+1); 
      memset(par, 0, len + 1); 
      method(par); 
      cout << "ret : " << par; 
     } 

     free(par); 
}