gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:47 26 4
gpt4 key购买 nike

那里。

我正在尝试制作一个程序,该程序读取 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com