我有一个函数
foo(void *buf) {
int i = 0;
unsigned char ptr = get_user_name();
//I want the buffer to hold user name from some position onwards
for(i=0;i<MESSAGE_LTH;i++)
*( (unsigned char*)(buf) + sizeof(some_struct)) ++ = ptr[i];
}
我收到错误:需要左值作为递增操作数
我希望缓冲区在结构之后不久保存用户名;
最佳答案
这个:
unsigned char ptr = get_user_name();
看起来应该是:
const unsigned char *ptr = get_user_name();
它必须是一个指针,因为您正在像访问它一样访问它。它应该是 const
,因为您只是从中读取。
复制应该使用 memcpy()
完成,之后递增指针可以单独完成:
unsigned char *put = buf; /* Proper type, for pointer arithmetic. */
put += sizeof(some_struct); /* Advance into the buffer. */
memcpy(put, ptr, MESSAGE_LTH); /* Do the copy. */
put += MESSAGE_LTH; /* Advance the pointer to after the name. */
当然在上面的最后,很难知道用put
做什么。也许从函数中返回它是有意义的,但您没有指定。
关于c - 取消引用强制转换的 void 指针并使用后增量运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26625904/