C语言中的游程长度译码
这是我的运行长度解码程序。但is将输出作为垃圾值。C语言中的游程长度译码,c,pointers,char,run-length-encoding,C,Pointers,Char,Run Length Encoding,这是我的运行长度解码程序。但is将输出作为垃圾值。char*decode_rle(char*a,int-length)方法中的输出是正确的,但返回到main函数时是错误的 #include<stdio.h> #include<string.h> char *decode_rle(char *a,int length) { char op[50]; int i,j,k=0,count=0; for(i=0;i<length;i++)
char*decode_rle(char*a,int-length)
方法中的输出是正确的,但返回到main函数时是错误的
#include<stdio.h>
#include<string.h>
char *decode_rle(char *a,int length)
{
char op[50];
int i,j,k=0,count=0;
for(i=0;i<length;i++)
{
if( a[i]=='a' || a[i]=='b' || a[i]=='c' || a[i]=='d' || a[i]=='e' || a[i]=='f' || a[i]=='g')
{
count = a[i+1] - '0';
for(j=0;j<count;j++)
{
op[k]=a[i];
k++;
}
}
}
op[k] = '\0';
printf("\n the decoded string is %s\n",op);
return op;
}
int main()
{
int i=0,j,length,count;
char a[20],*output;
printf("\n Enter a string ");
gets(a);
printf("\n The string you entered is %s",a);
length = strlen(a);
printf("\n length is %d\n",length);
output = decode_rle(a,length);
i=0;
while(output[i]!='\0')
{
printf("%c",output[i]);
i++;
}
getch();
return 0;
}
#包括
#包括
字符*解码(字符*a,整数长度)
{
char-op[50];
int i,j,k=0,count=0;
对于(i=0;i您试图返回一个变量,该变量的作用域仅为函数decode\rle
。您不能这样做,请确保安全。退出该函数时,程序将不再可以正式访问数组op
及其内容
您应该使用警告来编译-Wall
(您可以添加-Werror
来激发您的积极性)。您返回一个指向op
的指针,它是decode\rle()中的一个局部变量
。当函数返回且其内存将被重用时,此局部变量超出范围,因此指向该内存的指针不是很有用
相反,您可以使用malloc()
分配所需的内存并返回指向该内存的指针,或者向decode\rle()添加一个附加参数
将指针传递给应该写入结果的内存。问题在于,返回的是函数decode_rle的局部变量指针,一旦从该函数返回,该变量就不再存在
首先,我建议您将op声明为main的局部变量,并传递一个额外的参数来解码_rle
char *decode_rle(char *a,int length, char *op)
{
....
}
int main()
{
...
char op[50];
...
output = decode_rle(a,length, op);
}
字符*解码(字符*a,整数长度,字符*op)
{
....
}
int main()
{
...
char-op[50];
...
输出=解码(a,长度,op);
}
这将是可行的,但是…如果你需要的不仅仅是有限的概念证明,那么在这个练习中还有其他几个问题
- 如果a和p使用固定长度,如果用户在gets中输入长度超过20的字符串会发生什么?如果解码的字符串大于50会发生什么?
(请记住,c不进行数组边界检查,如果在不拥有的内存上写入,会发生什么情况?)
- 如何处理二进制0?(请记住,c中的字符串是使用asciiz约定存储的,如果试图压缩/解压缩的数据本身包含二进制0,会发生什么情况?如何更改缓冲区的定义以处理这种情况?)
另外,用fgets
替换gets
。