c - malloc 到 "array"指针的元素

标签 c pointers malloc dynamic-memory-allocation realloc

那里。

我正在尝试制作一个程序,该程序读取 N 个单词(当您键入 - 时结束)并按顺序打印。

我的问题是:我正在尝试使用某种动态的 char* 数组。它重新分配一个元素,但当我尝试在堆上为字符串创建空间时崩溃(第 21 行)。

可以修复吗?谢谢。

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

#define WORD_SIZE 11

int main()
{
        char word[WORD_SIZE];
        char **set;
        int j;
        int numberWord = 0;

        /* input */
        printf("Insert a word, or '-' to stop: ");
        fgets(word, WORD_SIZE, stdin);

        while (strcmp(word, "-\n")) {
                /* process */
                set = realloc(set, sizeof(char *) * (numberWord + 1));
                set[numberWord] = malloc(sizeof(char) * WORD_SIZE);
                numberWord++;

                /* input */
                printf("Insert a word, or '-' to stop: ");
                fgets(word, WORD_SIZE, stdin);
        }

        /* output */
        printf("\nSORTED:\n");
        for (j = 0; j <  numberWord; j++) {
                printf("%s", set[j]);
        }

        printf("\n");
        free(set);

        return 0;
}

最佳答案

realloc 要求重新分配的内存之前已经分配 ( see here )。

尝试在循环之前添加 set = malloc(1); 以预先分配至少 1 个字节。

关于c - malloc 到 "array"指针的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554657/

相关文章:

c++ - 2 昏暗数组和双指针

c++ - 需要制作一个已创建对象的数组

objective-c - Objective C 对象的 C 数组

c - c中数组的问题

C++ 内存管理

c - 释放使用双指针分配的结构数组

c - 关于malloc的问题

c - 函数中的段错误

c - x86-64 处理器的数据类型

c - R 中是否有比 readLines 更快的东西 - 或者我如何找出读取连接速度如此慢的原因?