压缩解压缩字符串(用zlib)解决方法
压缩解压缩字符串(用zlib)
用zlib压缩解压缩字符串,分别写了压缩与解压缩2个函数,但压缩后的码字似乎没能成功保存,以至于解压缩函数调用后没有结果。另外,关于malloc使用后需要free,当free的内存数据需要返回,怎么办?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"zlib.h"
unsigned long sourcelen;
unsigned long buflen;
char *compression(char *s)
{
char *buf=(char*)malloc(sizeof(char*)*sourcelen*2); //此处如何定义长度?压缩后长度可能变长(字符串较短时)
buflen=strlen(buf);
compress(buf,&buflen,s,sourcelen);
printf("%s",buf); //压缩后的字符串为乱码,用什么格式输出呢?“%s”可以吗?
return buf;
}
void *uncompression(char *buf)
{
char *dst=(char*)malloc(sizeof(char)*sourcelen);
unsigned long dstlen=strlen(dst);
uncompress(dst,&dstlen,buf,buflen);
printf("%s",dst);
}
int main()
{
char *p="adfga sdgdsdgg sdgki,oweutog;reyweu jfgdjghsdhdljjdgsdlglfjgljgp sudopuo pgjuas";
sourcelen=strlen(p)+1;
printf("%s\n",p);
char *d=(char*)malloc(sizeof(char)*sourcelen*2);
d=compression(p);
uncompression(d);
return 0;
}
函数之间的调用、值传递似乎有问题。望指教,谢谢!
------解决方案--------------------
是的。
用zlib压缩解压缩字符串,分别写了压缩与解压缩2个函数,但压缩后的码字似乎没能成功保存,以至于解压缩函数调用后没有结果。另外,关于malloc使用后需要free,当free的内存数据需要返回,怎么办?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"zlib.h"
unsigned long sourcelen;
unsigned long buflen;
char *compression(char *s)
{
char *buf=(char*)malloc(sizeof(char*)*sourcelen*2); //此处如何定义长度?压缩后长度可能变长(字符串较短时)
buflen=strlen(buf);
compress(buf,&buflen,s,sourcelen);
printf("%s",buf); //压缩后的字符串为乱码,用什么格式输出呢?“%s”可以吗?
return buf;
}
void *uncompression(char *buf)
{
char *dst=(char*)malloc(sizeof(char)*sourcelen);
unsigned long dstlen=strlen(dst);
uncompress(dst,&dstlen,buf,buflen);
printf("%s",dst);
}
int main()
{
char *p="adfga sdgdsdgg sdgki,oweutog;reyweu jfgdjghsdhdljjdgsdlglfjgljgp sudopuo pgjuas";
sourcelen=strlen(p)+1;
printf("%s\n",p);
char *d=(char*)malloc(sizeof(char)*sourcelen*2);
d=compression(p);
uncompression(d);
return 0;
}
函数之间的调用、值传递似乎有问题。望指教,谢谢!
------解决方案--------------------
是的。