简体   繁体   English

动态2D字符数组

[英]Dynamic 2D char array

I want to allocate my 2D char array dynamically. 我想动态分配我的2D char数组。 Here I try to do this in cycle, but it gets me segmentation fault error. 在这里我尝试在循环中执行此操作,但它会让我出现分段错误错误。 If I remove "arr[length] = str;" 如果我删除“arr [length] = str;” it will be ok. 一切都会安好的。 But it's not what I want to do. 但这不是我想要做的。

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

int main(void) {
    char** arr;
    int i = 0;
    int length = 0;
    for(i = 0; i < 4; i ++) {
        arr = (char**) realloc(arr, (length+1) * sizeof(char*));
        char* str = (char*) malloc(4 * sizeof(char));
        arr[length] = str;
    }

    return 0;
}

You can do what Guido said but you can instead also set initially 你可以做Guido所说的,但你最初也可以设置

char** arr = NULL;

because when realloc gets a NULL pointer as input it behaves as malloc. 因为当realloc获取NULL指针作为输入时,它表现为malloc。

Also the loop i assume must be 我假设的循环也必须如此

for(i = 0; i < 4; i ++) {
     arr = (char**) realloc(arr, (length+1) * sizeof(char*));
     char* str = (char*) malloc(4 * sizeof(char));
     arr[length++] = str;
}

Notice the length++. 注意长度++。

You're using realloc on a arr , but you never allocated space for it. 你在arr上使用realloc,但你从来没有为它分配空间。 Use malloc 使用malloc

According to manual: 根据手册:

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. realloc()函数将ptr指向的内存块的大小更改为size字节。 The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. 内容将在从区域开始到新旧尺寸的最小范围内保持不变。 If the new size is larger than the old size, the added memory will not be initialized. 如果新大小大于旧大小,则不会初始化添加的内存。 If ptr is NULL, then the call is equivalent to malloc(size), for all values of size ; 如果ptr为NULL,则对于所有size值,调用等效于malloc(size) ; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). 如果size等于零,并且ptr不为NULL,则该调用等效于free(ptr)。 Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). 除非ptr为NULL,否则必须由之前调用malloc(),calloc()或realloc()返回。 If the area pointed to was moved, a free(ptr) is done. 如果指向的区域被移动,则完成自由(ptr)。

So, to use realloc() you should pass NULL pointer at first call to it. 因此,要使用realloc()您应该在第一次调用时传递NULL指针。 Thus, arr should be initialized to NULL . 因此,应将arr初始化为NULL

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

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