gpt4 book ai didi

c - 分配给指针

转载 作者:行者123 更新时间:2023-11-30 19:40:52 26 4
gpt4 key购买 nike

我使用char ****pCourses

int Courses(char ****pCourses, int ****pGrades, int **pCount, int *count)
{
char *buffer=NULL;
char letter;
int j=0, i;
int size=20;
int countCourse=0, sumCourses=0;
buffer=(char *)malloc(size*sizeof(char));
do
{
scanf("%c",&letter);
}while(letter==32);
while(letter!=10)
{
while(letter!=',')
{
//in case we need to expend the buffer
if(j>size)
{
size*=2;
buffer=(char *)realloc(buffer,size*sizeof(char));
}
buffer[j]=letter;
j++;
//The new letter from the name of course
scanf("%c",&letter);
}
//The end of the name of course
buffer[j]='\0';
j=0;
if(countCourse==0)
{
*pCount=(int *)realloc(*pCount, ((*count)+1)*sizeof(int));
(*pCount)[*count]=1;
}
else
(*pCount)[*count]++;
//Add the course's name to the system
*pCourses=(char ***)realloc(*pCourses, ((*count)+1)*sizeof(char ***));
(*pCourses)[*count]=(char **)realloc((*pCourses)[*count],(countCourse+1)*sizeof(char *));
((*pCourses)[*count])[countCourse]=(char *)malloc(strlen(buffer)+1);
strcpy(((*pCourses)[*count])[countCourse], buffer);
countCourse++;
scanf("%c",&letter);
}
free(buffer);
return 0;
}

运行时我遇到了一个问题,因为下一行:

(*pCourses)[*count]=(char **)realloc((*pCourses)[*count],(countCourse+1)*sizeof(char *));

这引导我到这一部分(来自dbgheap.c):

{
while (nSize--)
{
if (*pb++ != bCheck)
{
return FALSE;
}
}
return TRUE;

}

有人知道这意味着什么或者为什么会发生这种情况吗?

最佳答案

我想您已经知道问题所在了。所有分配类型的函数都可能失败,您应该对此进行测试,并且最好编写足够健壮的代码,以应对失败的情况。

请注意,重复使用 realloc() 并不是一个好主意。如果您预计必须重复添加(或删除)数据,那么您应该使用不同的结构,例如链接列表或树,它们旨在允许动态添加和删除数据。

关于c - 分配给指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34398281/

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