【发布时间】:2013-07-18 11:06:01
【问题描述】:
我有以下用 C 语言编写的代码:
unsigned char * pan_protocol_get_image(unsigned long *psize)
{
long fsize;
unsigned char *result;
(void)pan_socket_write_ulong(MSG_GET_IMAGE);
pan_protocol_expect(MSG_IMAGE);
/* Read the size of the data in the message */
(void)pan_read_long(&fsize);
if (psize) *psize = fsize;
/*
* Allocate a buffer large enough for the result. We add one
* in case the size is zero because we need a valid pointer.
*/
result = (unsigned char *)malloc(fsize + 1);
/* Read the data directly into the result buffer */
(void)pan_read((void *)result, fsize);
return result;
}
据我所知,上面的函数返回一个指向一个字符的指针(而不是一个字符数组)。我对么?
如果是这样,如何将函数结果(即指向字符的指针)转换为字符数组,以便我可以一个一个地读取它们?
【问题讨论】:
-
从技术上讲,它是一个指向字符的指针。准确地说,它指向一个字符所在的内存位置。但是,没有什么可以阻止该字符后面跟着一些其他字符 - 这是有道理的,因为分配给
malloc的内存块似乎比1大。您可能可以通过该指针有效地访问一个字符数组。 -
上面的代码实际上是指向一个字符流/数组,而不是单个字符。因此您可以读取作为字符数组返回的结果。
-
鉴于它确实 malloc(fsize + 1);,我想知道是否打算添加尾随 \0