我有一個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
字符串。但是,在循環之外,所有存儲的值似乎都消失了。我正在考慮範圍,但無法弄清楚原因。有人可以解釋我應該如何正確地做到這一點?謝謝!
[不投malloc'的'結果。(http://stackoverflow.com/questions/605845/do- i-cast-of-malloc的結果)你在哪裏離開'while循環? – pzaenger
我明白了。謝謝你教我。對不起,已編輯。 – Ra1nWarden
源和dest == a和b? –