【问题标题】:Run length encode in C, Problem with strcatC中的运行长度编码,strcat的问题
【发布时间】: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


【解决方案1】:
malloc(sizeof(encode))

sizeof(encode) 是指针的大小,所以你只为它分配 4 或 8 个字节。

我认为您还必须从 0 开始,而不是从 1 开始计数器 i 和 z。

编辑: 问题很多,我没有全部标出来。

【讨论】:

  • 谢谢,我刚刚把 sizeof(encode) 改成了 sizeof(char)
  • 我想知道连续的char个数,所以z要从1开始
  • @D.J.A.:你知道sizeof(char) 是1,不是吗?这足以容纳空终止符,仅此而已。在最坏的情况下,当没有连续字符时,您将需要2 * strlen(line) + 1 个字符。
  • @D.J.A.为避免@MOehm 提到的最坏情况分配,您可以执行两次。第一遍将计算出所需的缓冲区长度。然后,在分配缓冲区后,第二遍将填充它。为了在单遍中完成,您需要分配一个足够大小的缓冲区来处理最坏的情况,但您可以调用realloc 来减小缓冲区大小之后调整到所需的大小。
【解决方案2】:

这不是您问题的完整答案,因为您的代码中还有许多其他问题。

这个小程序展示了如何将char 附加到字符串以及如何将int 的十进制表示附加到字符串。

#include <stdio.h>
#include <string.h>

int main(void)
{
  char encode[100] = "abc";

  printf("%s\n", encode);

  // append the char 'X' to the encode string
  int len = strlen(encode);
  encode[len] = 'X';
  encode[len + 1] = 0;       // put the NUL terminator

  printf("%s\n", encode);

  // append the decimal representation of the int y to encode

  int y = 123;
  char *p = encode + strlen(encode);
  sprintf(p, "%d", y);

  printf("%s\n", encode);
}

输出:

abc
abcX
abcX123

你真的需要学习 C 的基础知识。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2012-07-11
    • 1970-01-01
    相关资源
    最近更新 更多