我的代码中有任何问题或需要改进吗?
#include <stdio.h>
#include <stdlib.h>
char * filterdupchar(char* s,int n){
char *tmp2 = s ;
char *tmp =(char*)malloc(n*sizeof(char));
for(int j=0;j<n/2;j++){
int i=0,p=0;
while(i<n){
*(tmp+p) = s[i];
if(s[i]==s[i+1])
i = i+2;
else
i++;
p++;
}
s = tmp;
}
s = tmp2;
return tmp;
}
int main(){
char * str= "bbaaan";
printf("%s",str);
printf("\n");
char * strnew;
strnew = filterdupchar(str,6);
printf("%s",strnew);
return 1;
}
结果应该是&#34;禁止&#34;,但它附加到某些无序的字符上。 在我的函数中,是否有必要给tmp2,我需要释放吗?
答案 0 :(得分:2)
<强>更改强>
<强>码强>
detailTextLabel
<强>输出强>
#include <stdio.h>
#include <stdlib.h>
char * filterdupchar(char* s,int n)
{
int from,to; char last;
char *tmp = malloc((n+1)*sizeof(char));
from = to = 0;
last = 0;
for(from = 0; from < n; from++)
{
if(s[from] != last)
{
tmp[to] = s[from];
to++;
}
last = s[from];
}
tmp[to] = '\0';
return tmp;
}
int main()
{
char * str= "bbaaan";
printf("%s\n",str);
char * strnew;
strnew = filterdupchar(str,6);
printf("%s\n",strnew);
free(strnew);
return 0;
}
备注强>
总是使用内存检查程序(如valgrind)来测试内存泄漏