我有以下代碼寫入C:字符指針成char陣列
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'。您可能可以通過該指針有效地到達一組字符。 – Nbr44
上面的代碼實際上是指向一個字符流/數組而不是單個字符。所以你可以讀取字符數組返回的結果。 – Jack
鑑於它做malloc(fsize + 1);,我想知道是否意圖添加尾隨\ 0 – doctorlove