Выполнить кодирование длины в C, проблема с strcat - PullRequest
0 голосов
/ 12 февраля 2019

Я пытаюсь написать программу кодирования длин серий в C.

Для ввода 'ABBCD' я ожидаю следующий результат: 'A1B2C1D1'

Я сдаю два- строка массива char для строки функции, которая кодирует символы:

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?

Ответы [ 2 ]

0 голосов
/ 12 февраля 2019

Это не полный ответ на ваш вопрос, потому что в вашем коде много других проблем.

Эта небольшая программа показывает, как добавить 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.

0 голосов
/ 12 февраля 2019
malloc(sizeof(encode))

sizeof (кодировать) - это размер указателя, поэтому вы выделяете для него только 4 или 8 байтов.

Я думаю, что вы также должны начинать счетчики i и z с 0,не от 1.

РЕДАКТИРОВАТЬ: Есть много проблем, я не пометил их всех.

...