2014-01-19 70 views
-1

我有一個struct複製串入結構ç

typedef struct myStruct { 
    char** a; 
    char** b; 
} myStruct; 

我試圖從stdin讀取和初始化的myStruct*

int main() { 
    int maxlength = 60 + 1; 
    int arraySize = 2; 
    myStruct** myArray = (myStruct*) malloc(sizeof(myStruct*) * arraySize); 
    int runningIndex = 0; 
    while(1) { 
    char* aline = (char*) malloc(maxlength); 
    int status = getline(&aline, &maxlength, stdin); 
    if(status == -1) 
     break; 
    char* bline = (char*) malloc(maxlength); 
    getline(&bline, &maxlength, stdin); 
    if(runningIndex == arraySize) { 
     arraySize *= 2; 
     myArray = realloc(myArray, sizeof(myStruct*) * arraySize); 
    } 
    myArray[runningIndex] = (myStruct*) malloc(sizeof(myStruct*)); 
    myArray[runningIndex]->a = &aline; 
    myArray[runningIndex]->a = &bline; 
    runningIndex++; 
    } 
    for(int i = 0; i < runningIndex; i++) { 
    printf("outside the loop at index %d, a is %s and b is %s", i, *myArray[i]->a, *myArray[i]->b); 
    } 
} 

一個數組,我做了while在幾printf確認每個myStruct成功創建與從stdin字符串。但是,在循環之外,所有存儲的值似乎都消失了。我正在考慮範圍,但無法弄清楚原因。有人可以解釋我應該如何正確地做到這一點?謝謝!

+0

[不投malloc'的'結果。(http://stackoverflow.com/questions/605845/do- i-cast-of-malloc的結果)你在哪裏離開'while循環? – pzaenger

+0

我明白了。謝謝你教我。對不起,已編輯。 – Ra1nWarden

+0

源和dest == a和b? –

回答

0

樣來解決:

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

typedef struct myStruct { 
    char *a; 
    char *b; 
} myStruct; 

int main() { 
    int maxlength = 60 + 1; 
    int arraySize = 2; 

    myStruct* myArray = malloc(sizeof(myStruct) * arraySize); 
    int runningIndex = 0; 
    while(1) { 
     char *aline = malloc(maxlength); 
     int status = getline(&aline, &maxlength, stdin); 
     if(status == -1) 
      break; 
     char *bline = malloc(maxlength); 
     getline(&bline, &maxlength, stdin); 
     if(runningIndex == arraySize) { 
      arraySize *= 2; 
      myArray = realloc(myArray, sizeof(myStruct) * arraySize); 
     } 
     myArray[runningIndex].a = aline;//&aline is address of local variable. 
     myArray[runningIndex].b = bline;//And content is rewritten in each loop. 
     runningIndex++; 
    } 
    for(int i = 0; i < runningIndex; i++) { 
     printf("outside the loop at index %d, a is %s and b is %s", i, myArray[i].a, myArray[i].b); 
    } 
    //deallocate 
    return 0; 
} 
0

單個字符串指針的定義如下:

char *pStr; 

字符串指針的陣列的定義如下:

char **pStrArr; 

要爲一個字符串動態地創建存儲器,這樣做:

pStr = malloc(STRING_LEN); 

要爲字符串數組動態創建內存,請執行以下操作:

pStrArr = (NUM_STRINGS * (*pStrArr)); 
for(str = 0; str < NUM_STRINGS; str++) 
    pStrArr[str] = malloc(STRING_LEN); 

在你的情況,你需要爲你的struct或兩個數組char串的,無論你的要求是以下兩種char字符串。它看起來像你真的只需要兩個單一的字符串。如果是這樣,這樣做:

typedef struct 
{ 
    char* a; 
    char* b; 
} myStruct; 

myStruct structure; 

structure.a = malloc(STRING_LEN); 
structure.b = malloc(STRING_LEN); 
+0

'pStrArr =(NUM_STRINGS *(* pStrArr));'? – zoska

+0

@zoska在這種情況下,相當於'char *'。 –