c - 取消引用强制转换的 void 指针并使用后增量运算符

标签 c pointers void-pointers

我有一个函数

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/

相关文章:

c - 动态分配结构体指针数组,指向它们并对它们进行排序

c - 访问 vector 中结构的成员

c++ - 将指针传递给函数 C++ SDL2

c - C 中使用指向 char 的指针的通用交换函数

c - 在 void 指针中存储和打印字符串

com - 如何在 IDL 中声明 void* 类型的参数

计算不重叠的连续 1 位

c++ - 2 个项目可以在 MS VS 2008 中创建一个 dll 吗?

c - 带有 typedef 结构的 extern const

c++ - 如何确定缓存的阻塞因子