【发布时间】:2019-02-12 09:50:51
【问题描述】:
我正在尝试用 C 编写一个行程编码程序。
对于输入“ABBCD”,我希望得到以下结果:“A1B2C1D1”
我将一个二维字符数组 line for line 交给对字符进行编码的函数:
for(i; i <= curline; i++) //hand over line for line
{
encoded->lines[i] = malloc(255);
encoded->lines[i] = rle_encode(read->lines[i]); //read->lines contains the characters of each line
printf("%s", encoded->lines[i]); // print out the result returned by the function rle_encode
}
我已经对此进行了测试,并且知道它会起作用。
现在这是我的函数 rle_encode:
char *rle_encode(char *line){
char *encode = malloc(sizeof(2 * strlen(line) + 1));
char prev = line[0]; //here I want to save the previous character
int i = 0;
int z = 1;
do{
i++;
if(prev == line[i]) // if character n equals n-1 (previous)
{
z++; // increase counter varaible z
}else
{
strcat( encode, line[i] ); //the content of line[i] will be append to the array encode
strcat( encode, z ); //also the counter variable will be appended
}
prev = line[i];
}while(line[i] != '\n'); //in the end of each line a '\n' appears, if line[i] is '\n' it should stop the function
return encode;}
函数rle_encode有什么问题?
【问题讨论】:
-
加上你的指针
encode分配错误sizeof (encode)相当于sizeof(char*),这可能不是你想要的。 -
您的代码无法编译且不完整。请发布真实代码。阅读此:How to Ask 和此:minimal reproducible example。
-
@D.J.A.there is 没有返回类型,这就是问题所在。 C 不正确。
-
if(prev = line[i])嗯... -
您正在对未初始化的目标缓冲区调用
strcat。您应该在do {循环之前设置encode[0] = '\0';。
标签: c string pointers malloc strcat