[英]Casting from const void to char?
好吧,我正在對圖像進行哈希處理。 眾所周知,對圖像進行哈希處理需要FOREVER 。 因此,我要拍攝100張均勻分布的圖像樣本。 這是代碼。
#define NUM_HASH_SAMPLES 100
@implementation UIImage(Powow)
-(NSString *)md5Hash
{
NSData *data = UIImagePNGRepresentation(self);
char *bytes = (char*)malloc(NUM_HASH_SAMPLES*sizeof(char));
for(int i = 0; i < NUM_HASH_SAMPLES; i++)
{
int index = i*data.length/NUM_HASH_SAMPLES;
bytes[i] = (char)(data.bytes[index]); //Operand of type 'const void' where arithmetic or pointer type is required
}
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( bytes, NUM_HASH_SAMPLES, result );
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
錯誤在注釋行上。
我究竟做錯了什么?
data.bytes
是一個void *
,因此取消引用(甚至對其執行必要的指針算術運算)是沒有意義的。
因此,如果您打算從數據中取出一個字節,則獲取一個指向const unsigned char
的指針並取消引用:
const unsigned char *src = data.bytes;
/* ..then, in your loop.. */
bytes[i] = src[index];
哦, 不要轉換malloc()
的返回值 !
根據NSData的文檔, data.bytes
返回const void *
的類型。 基本上,您正在嘗試訪問指向void
的指針,這是沒有意義的,因為void
沒有大小。
將其強制轉換為char指針並取消引用。
((const char *)data.bytes)[index]
要么
*((const char *)data.bytes + index)
編輯:我通常要做的是立即將指針分配給已知數據類型,然后改用它。
即
const char *src = data.bytes;
bytes[i] = src[index];
Edit2:您可能還想保留H2CO3建議的const
限定符。 這樣,您就不會意外地寫到您不應該寫的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.