-2
我想每次輸入一個字符到每個塊每行,但是會發生什麼是最後一行將覆蓋我存儲在前一行中的以前的內容。最後,我所有的行都有相同的內容..有人可以解釋我做錯了什麼嗎?爲什麼我的雙指針會覆蓋它的行?
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
int row=0,col=0,i;
char c;
char **this=NULL;
this=calloc(64,sizeof(char*));
for(i=0;i<64;++i)
{
this[i]=calloc(5,sizeof(char));
free(this[i]);
}
while(c!=EOF)
{
c=getchar();
if(!isspace(c)&&isprint(c))
{
if(c==',')
{
this[row][col]='\0';
row++;
col=0;
}
else if(c=='.')
{
this[row][col]=c;
this[row][col+1]='\0';
}
else
{
this[row][col]=c;
//printf("%d,%d\n",row, col);
//printf("%c\n",this[row][col]);
//printf("%s\n",this[row]);
//printf("%s\n",this[row+1]);
col++;
}
}
}
printf("string0:%s\n",this[0]);//prints the same thing
printf("string1:%s\n",this[1]);
free(this);
return 0;
}
分配之後,「free(this [i])'是什麼意思?您之後對任何指針的使用都是未定義的行爲。 –
我知道,每當我分配,我需要釋放它,所以我仍然可以重用的空間?但我真的不知道我應該在哪裏釋放它。 –
當你完成它的時候,你釋放內存。如果您嘗試在釋放後使用分配的內存(以及指針對象),則這是未定義的行爲。 –