【发布时间】:2011-10-24 21:43:34
【问题描述】:
我正在为一个项目创建一个图像压缩器。我为图像中的值生成代码的方式是,对于每个灰度值(从 0 到 254),在一个名为 codeArray(Huffman 编码)的数组中都有一个 char* 代码。
要求有一个返回 unsigned char* 的函数。我遍历每个像素并使用 codeArray 将该像素的灰度值转换为代码。
我需要使 unsigned char 数组随着更多灰度值被转换并连接到数组末尾而动态增长。
unsigned char* encodedString = malloc(sizeof(char));
int width = image->width; //width and height of image structure
int height = image->height;
int row, col;
for(row = 0; row<height; row++)
for(col = 0; col<width; col++)
{
int value = image->pixel[row][col]; //gets the grey value
encodedString = realloc(encodedString, (strlen(encodedString)+strlen(codeArray[value])));
strcat(encodedString, codeArray[value]);
}
我尝试在 strcat 之后使用 print 语句运行它,发现它一直打印到有 24 个字符,然后开始打印垃圾,然后 Seg 出现故障。
帮助表示赞赏!
【问题讨论】: