程序的功能是输入字符串存入pS指针,进行大小对比后按从小到大输出。发现当输入字符串超过5个时程序会停止运行,恳请哪位大神帮我看下代码有什么问题。
代码如下:
#include
#include
#include
#define BUF_LEN 100
#define COUNT 5
int main(void)
{
char buf[BUF_LEN];
size_t str_count=0;
size_t capacity=COUNT;
char pS=(char)calloc(capacity,sizeof(char*));
char** psTemp=NULL;
char* pTemp=NULL;
size_t str_len=0;
bool sorted=false;
printf("Enter strings to be sorted,one per line.Press Enter to end:\n");
char ptr=NULL;
while(true)
{
ptr=fgets(buf,BUF_LEN,stdin);
if(!ptr)
{
printf("Error reading string.\n");
free(pS);
pS=NULL;
return 1;
}
if(*ptr=='\n') break;
if(str_count==capacity)
{
capacity+=capacity/4;
if(!(psTemp=(char*)realloc(pS,capacity))) return 1;
pS=psTemp;
}
str_len=strlen(buf)+1;
if(!(pS[str_count]=(char*)malloc(str_len))) return 2;
strcpy(pS[str_count++],buf);
}
while(!sorted)
{
sorted=true;
for(size_t i=0;i {
if(i==(str_count-1))
break;
if(strcmp(pS[i],pS[i+1])>0)
{
sorted=false;
pTemp=pS[i];
pS[i]=pS[i+1];
pS[i+1]=pTemp;
}
}
}
printf("Your input sorted in ascending sequence is:\n\n");
for(size_t k=0;k<str_count;++k)
{
printf("%s",pS[k]);
free(pS[k]);
pS[k]=NULL;
}
free(pS);
pS=NULL;
return 0;
}
如果实在搞不懂 realloc 是如何运行的,但又担心是它引起的错误,可以考虑自己用 calloc 代替:申请一块大的空间,将以前空间中的数据复制到新申请的空间中,再释放以前的空间。
因为你calloc只分配了5个大小的空间,超过5个,这个指针就被破坏了,已经不是最初始的ps了,这样你对他进行释放就会出错,你调试一下你的程序,看看是什么地方报错,然后在确定是因为容量问题还是指针飞掉的问题