动态增长的char问题C

时间:2015-01-24 13:48:45

标签: c arrays dynamic-arrays

我似乎在c中使用动态增长的数组时遇到了一些麻烦,使用它作为参考:C dynamically growing array

请你帮我告诉我,我为此犯了什么错误?

struct fileData {
  char *data;
  size_t used;
  size_t size;
};

void initData(struct fileData *a, size_t initialSize) {
  a->data = malloc(initialSize * sizeof(char));
  if(a->data == NULL) {
        printf("ERROR: Memory allocation failure!\n");
        exit(1);
  }
  a->used = 0;
  a->size = initialSize;
}

void insertLine(struct fileData *a, char *element) {
  if(a->used == a->size) {
    /*a->size = (a->size*3)/2+8;*/
        a->size *= 2;
    a->data = realloc(a->data, a->size * sizeof(char));
    if(a->data == NULL) {
        printf("ERROR: Memory allocation failure!\n");
        exit(1);
    }
  }
  a->data[a->used++] = *element;
}

void freeData(struct fileData *a) {
  free(a->data);
  a->data = NULL;
  a->used = a->size = 0;
}

使用的代码:

struct fileData *fileData = NULL;
fileData = malloc(sizeof(struct fileData));
if(fileData == NULL) {
    printf("Memory allocation issues\n");
    return FALSE;
}

initData(fileData, 5); /* 5 lines */

insertLine(fileData, "Test");
printf("%s\n", fileData->data);

printf返回“T”,而我想将多个字符串存储到这个动态增长的数组中。请帮帮我!

1 个答案:

答案 0 :(得分:1)

如果您要存储多个字符串,则data字段应该是char **而不是char *,您应该复制字符串,而不是分配data }字段指向传递的指针。

试试这个

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

struct fileData {
    char **data;
    size_t used;
    size_t size;
};

void initData(struct fileData *a, size_t initialSize) {
    a->data = malloc(initialSize * sizeof(char *));
    if (a->data == NULL) {
        printf("ERROR: Memory allocation failure!\n");
        exit(1);
    }
    a->used = 0;
    a->size = initialSize;
}

void insertLine(struct fileData *a, char *element) {
    if(a->used == a->size) {
        void *pointer;

        a->size *= 2;
        pointer  = realloc(a->data, a->size * sizeof(char *));
        if (a->data == NULL) {
            freeData(a);

            printf("ERROR: Memory allocation failure!\n");
            exit(1);
        }
        a->data = pointer;
    }
    /* if the string passed is not NULL, copy it */
    if (element != NULL) {
        size_t length;

        length           = strlen(element);
        a->data[a->used] = malloc(1 + length);
        if (a->data[a->used] != NULL)
            strcpy(a->data[a->used++], element);
    }
    else
        a->data[a->used++] = NULL;
}

void freeData(struct fileData *a) {
    size_t i;
    /* Free all the copies of the strings */
    for (i = 0 ; i < a->used ; ++i)
        free(a->data[i]);
    free(a->data);
    free(a);
}

int main(void) {
    struct fileData *fileData = NULL;

    fileData = malloc(sizeof(struct fileData));
    if (fileData == NULL) {
        printf("Memory allocation issues\n");
        return -1;
    }
    initData(fileData, 5); /* 5 lines */

    insertLine(fileData, "Test");
    printf("%s\n", fileData->data[0]);

    freeData(fileData);

    return 0;
}