2012-04-30 62 views
0

我想用函數重新分配一個字符串數組。我寫了一個非常簡單的程序來演示這裏。我期望得到字母「b」被輸出,但我得到NULL。C:重新分配一個字符串數組

void gain_memory(char ***ptr) { 
    *ptr = (char **) realloc(*ptr, sizeof(char*) * 2); 
    *ptr[1] = "b\0"; 
} 

int main() 
{ 
    char **ptr = malloc(sizeof(char*)); 
    gain_memory(&ptr); 
    printf("%s", ptr[1]); // get NULL instead of "b" 
    return 0; 
} 

非常感謝!

+1

不要強制返回'realloc',畢竟這是C語言。 (這樣做可能會隱藏編譯器會告訴你的問題。) –

+0

另外,不要將realloc的結果立即分配給要重新分配的指針。如果'realloc'失敗,你就失去了原來的指針並泄漏了內存。 (哦,並檢查分配是否失敗。) – jamesdlin

回答

0

你應該把周圍* PTR括號中gain_memory:

(*ptr)[1] = "b\0"; 
0

你不分配您的字符串數組中的實際字符串的所有記憶,你需要做的是這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

void gain_memory(char ***ptr, int elem) { 
    *ptr = (char**)realloc(*ptr, 2*elem*sizeof(char*)); 
    (*ptr)[1] = "b"; 
} 

int main() 
{ 
    //How many strings in your array? 
    //Lets say we want 10 strings 
    int elem = 10; 
    char **ptr = malloc(sizeof(char*) * elem); 
    //Now we allocate memory for each string 
    for(int i = 0; i < elem; i++) 
     //Lets say we allocate 255 characters for each string 
     //plus one for the final '\0' 
     ptr[i] = malloc(sizeof(char) * 256); 

    //Now we grow the array 
    gain_memory(&ptr, elem); 
    printf("%s", ptr[1]); 
    return 0; 
} 
+0

他不需要爲示例中的實際字符串分配內存,因爲他只將一個常量字符串分配給其中一個指針。 – JeremyP

3

[]運算符比*有更高的優先級,所以像這樣改變代碼將會正常工作。

(*ptr)[1] = "b"; 

P.S. 「\ 0」是不必要的。

相關問題