2014-01-19 67 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 *'。 –