将字符串复制到struct C中

时间:2014-01-19 17:11:29

标签: c string struct

我有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);
  }
}

我在printf中做了一些while,以确认使用myStruct中的字符串成功创建了每个stdin。但是,在循环之外,所有存储的值似乎都消失了。我在考虑范围,但无法弄清楚原因。有人可以解释我将如何正确地做到这一点?谢谢!

2 个答案:

答案 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);

在您的情况下,无论您的要求是什么,都需要为char或两个struct字符串数组创建两个char字符串。看起来你真的只需要两个单字符串。如果是这样,请执行以下操作:

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

myStruct structure;

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

答案 1 :(得分: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;
}