简体   繁体   English

插入到 C 中的动态字符串数组

[英]Insert to a dynamic array of strings in C

I'm trying to implement a dynamic array of strings.我正在尝试实现一个动态的字符串数组。 However I encountered a slight problem.但是我遇到了一个小问题。 I don't allocate the memory properly, but I have no idea what am doing wrong.我没有正确分配 memory,但我不知道做错了什么。

My structure for the dynamic array looks like:我的动态数组结构如下:

typedef struct Array {
    char **ids;
    int size;
} dynamicArray;

I initialize it with:我初始化它:

void initArray(dynamicArray *array) {
    array = malloc(sizeof(dynamicArray));
    array->ids = NULL;
    array->size = 0;
}

Deallocate by:通过以下方式解除分配:

void freeArray(dynamicArray *array) {
    if (array->size != 0) {
        for (int i = 0; i < array->size; i++) {
            free(array->ids[i]);
        }
        array->size = 0;
        array->ids = NULL;
    }
}

But now the real problem for me is inserting:但现在对我来说真正的问题是插入:

void insertArray(dynamicArray *array, char *name) {
    if (array == NULL) {
        return;
    }
    int length = strlen(name) + 1;
    array = realloc(array, (??));
    strcpy(array->ids[array->size++], name);
}

The program fails on the reallocation with: Exception has occurred.程序在重新分配时失败: Exception has occurred. . . I'm really not sure, what am I doing wrong.我真的不确定,我做错了什么。 I know I should be also allocating the array of string, but have no idea how to put it in there.我知道我也应该分配字符串数组,但不知道如何把它放在那里。 Could you guys please send me any hints??你们能不能给我任何提示?

The pointer that you need to reallocate is array->ids , not array .您需要重新分配的指针是array->ids ,而不是array When you insert into the array you increase its size.当您插入数组时,您会增加其大小。 Then the new element points to a copy of the name string.然后新元素指向name字符串的副本。

void insertArray(dynamicArray *array, char *name) {
    if (array == NULL) {
        return;
    }
    int length = strlen(name) + 1;
    char *copy = malloc(length);
    if (copy == NULL) { // malloc failed
        return;
    }
    strcpy(copy, name);
    char **new_ids = realloc(array->ids, (array->size+1) * sizeof(char *));
    if (new_ids == NULL) { // realloc failed
        return;
    }
    array->ids = new_ids;
    array->ids[array->size++] = copy;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM