gpt4 book ai didi

c - C双指针重新分配错误

转载 作者:行者123 更新时间:2023-12-02 09:26:21 26 4
gpt4 key购买 nike

friend 你好:)我正在练习C编程。在这个程序中,我有一个任务来制作字符串数组。我不知道这是怎么回事...大概是关于realloc的问题,我得到的错误是_crtisvalidheappointer

#define _CRT_SECURE_NO_WARNINGS
#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void readString(char **s)
{
int i = 0;
char c;
printf("\nInput string: ");
while ((c = getchar()) != '\n')
{
i++;
*s = realloc(*s, i*sizeof(char*));
if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
(*s)[i - 1] = c;
}
*s = realloc(*s, (i + 1)*sizeof(char));
if (*s == NULL) { printf("Memory allocation failed!"); exit(1); }
(*s)[i] = '\0';
}


char **load_words()
{
int cnt=0,wordcnt=0,i=0;
char **words = NULL, *input = NULL;
readString(&input);
while (input[cnt] != '\0' && cnt < strlen(input))
{
words = realloc(words, ++wordcnt);//errors in second repeat of the loop
words[wordcnt] = malloc(MAX);
i = 0;
while (input[cnt] != ' ')
{
words[wordcnt][i++] = input[cnt++];
}
words[wordcnt][i] = '\0';
realloc(words[wordcnt], (i + 1)*sizeof(char));
}
realloc(words, wordcnt);
free(input);
return words;
}

void main()
{
int i;
char **words = NULL;
words = load_words();
scanf("%d", &i);
}

有人可以帮助我,告诉我我在这里做错了什么吗?此函数应返回字符串数组,但数组应为双指针(字符串矩阵)

最佳答案

你需要改变

words = realloc(words, ++wordcnt);


words = realloc(words, ++wordcnt * sizeof(*words));

否则,您将无法分配足够的内存。
words[wordcnt] = malloc(MAX);

这也不正确,您应该访问 words[wordcnt-1]

关于c - C双指针重新分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716580/

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