gpt4 book ai didi

C - 压缩字符的函数

转载 作者:行者123 更新时间:2023-11-30 21:06:23 24 4
gpt4 key购买 nike

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

char * compress(char *input, int size){

char *inputa;
char compressedString[100];
inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);
int i = 0;
int x;
int counter;

while(i < size){
counter = 1;
x = i;
while (inputa[x] == inputa[x + 1] && (x+1) < size){
x++;
counter++;
}
if (i != x){
i = x;
}else{
i++;
}
}
return inputa;
}

main(){

char ez[] = "blaablaaa";

printf("%s \n", compress(ez, sizeof(ez)));
printf("%s", ez);

return 0;
}

所以,我试图使这个函数压缩连续字符(例如,“blaablaaa”“bla2bla3”)。我的思考过程是将 inputa[x] 放在压缩数组上,并在其旁边放置计数器,但我似乎无法使其工作。

最佳答案

让我们看一下这两行:

inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);

size 的类型为 int,因此 sizeof(size) 是整数的大小,可能是 4。

您使用malloc分配了4个字节。

然后,您使用 snprintf 尝试将所有输入(blaablaaa,10 字节长)复制到只有 4 字节长的缓冲区中。

4 字节缓冲区无法容纳 10 个字节。

我不确定你想在那里做什么,但这是不正确的。

关于C - 压缩字符的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com