c - 当尝试实现字符串数组时我做错了什么?

标签 c memory dynamic struct allocation

typedef struct ArrayList
{
    // We will store an array of strings (i.e., an array of char arrays)
    char **array;

    // Size of list (i.e., number of elements that have been added to the array)
    int size;

    // Length of the array (i.e., the array's current maximum capacity)
    int capacity;

} ArrayList;

以下函数应该为包含结构的头文件支持的字符串数组动态分配内存(见上文):

void panic(char *s)
{
    fprintf(stderr, "%s", s);
    exit(1);
}

ArrayList *createArrayList(int length){
    ArrayList *n = malloc(sizeof(ArrayList));

    int initial = 0, i;

    if (length > DEFAULT_INIT_LEN)
    {
        n->array = (char **)malloc(length * sizeof(int*));
        n->capacity = length;

        for (i = 0; i< n->capacity; i++)
        {
            n->array[i] = NULL;
        }
    }
    else
    {
        n->array = (char **)malloc(DEFAULT_INIT_LEN * sizeof(int*));
        n->capacity = DEFAULT_INIT_LEN;

        for (i = 0; i< n->capacity; i++)
        {
            n->array[i] = NULL;
        }
    }

    if (n->array == NULL)
        panic("ERROR: out of memory in Mylist!\n");

    n->size = initial;

    printf("-> Created new ArrayList of size %d\n", n->capacity);
    return n;
}

然后我有另一个函数,它应该打印当前由 createArrayList 函数创建的新分配的数组中的所有字符串:

void printArrayList(ArrayList *list)
{
    int i;

    for(i=0; i<list->capacity; i++)
    {
        if (list->array[i] == NULL)
            printf("(empty list)\n");
        else
            printf("%s\n",list->array[i]);

    }
}

当我在主函数中实现 printArrayList 函数(上面)时,输出为:

-> Created ArrayList of size 10 
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)

但是,如果我在 createArrayList 函数中插入 strcpy(n->array[1], "apple"); 作为测试 2D 数组保存字符串的能力的方法,则输出为:

-> Created ArrayList of size 10 

...然后就崩溃了

所以我的问题是我做错了什么?我是否错误地为阵列分配了内存?我想得到它,所以输出是:

-> Created ArrayList of size 10 
(empty list)
apple
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)
(empty list)

最佳答案

除了为ArrayList分配内存之外,您还需要为每个字符串分配存储空间。如果你想设置数组的第二个元素,你可以使用类似的东西来做到这一点

void insert_at(ArrayList* arraylist, const char* str, int index)
{
    arraylist->array[index] = malloc(strlen(str)+1);
    if (arraylist->array[index] != NULL) {
        strcpy(arraylist->array[index], str);
    }
}

并这样调用它

insert_at(n, 1, "apple");

顺便说一句,你的代码就像

n->array = (char **)malloc(length * sizeof(int*));

应该是

n->array = malloc(length * sizeof(char*));

(它是指向 char 而不是 int 的指针数组,并且您不应该在 C 中强制转换 malloc 的返回值)

关于c - 当尝试实现字符串数组时我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778958/

相关文章:

c - 打印到 stderr 时检查 fprintf 时出错

iPhone 应用程序在附加图像并在 uiwebview 中加载时占用大量内存

c - 在没有内存泄漏的情况下替换函数中的 char*

php - Laravel 模型动态属性

swift - 通过 Action 使 SKPhysicsBody 充满活力

c - 如何检测 GSM 调制解调器响应的最后一个字符

c - OS X Yosemite 上的堆栈崩溃?

c - 打印 C 指针的物理地址

.net - 内存随机化作为应用程序安全增强?

jquery - 在页面刷新时加载不同的图像