c - 在c中重新分配二维字符数组

标签 c arrays malloc free realloc

我在重新分配数组时遇到问题。我想将输入保存到字符串数组中,并为每个新条目重新分配它。 这是我的功能:

char** history=0;

int historycounter=0;

void saveHistory(char* input){

    history=(char**)realloc(history,sizeof(*history)+sizeof(input)*sizeof(char));
    history[historycounter]=(char*)malloc(sizeof(input)*sizeof(char));
    strcpy(history[historycounter],input);
    historycounter++;
}

最佳答案

试试这个

void saveHistory(const char *input){
    size_t size = strlen(input)+1;
    history = realloc(history, sizeof(*history)*(historycounter+1));
    history[historycounter] = malloc(size);
    memcpy(history[historycounter], input, size);
    historycounter++;
}

关于c - 在c中重新分配二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140782/

相关文章:

linux - malloc_trim() 可以从堆中间释放内存吗?

子进程在协进程中读取后挂起

c++ - 如何从 C 调用用 C++ 编写的库?

c - 函数 : findnextchar() doesn't work

file - 如何将内存流加载到 LibVLC 中?

PHP 不区分大小写的 in_array 函数

c - 如何在结构中分配固定大小的二维数组?

c - 如何在另一个函数中使用带有存储的来自一个函数的用户输入的变量?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - 依次调用malloc和free函数是否会产生内存碎片?