【问题标题】:Dereferencing a casted void pointer and using post increment operator取消引用强制转换的 void 指针并使用后增量运算符
【发布时间】:2014-10-29 08:41:44
【问题描述】:

我有一个功能

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];
}

我收到error: lvalue required as increment operand 我希望缓冲区在结构之后立即保存用户名;

【问题讨论】:

  • 打算做什么?
  • @timrau 缓冲区的前几个字节将保存 (some_struct) 数据并且结构的类型会发生变化,所以我希望用户名在缓冲区中的结构之后很快出现。
  • 你知道为什么n++ = 10; 不起作用吗?
  • @KerrekSB 是的,我明白这一点!我无法根据我的要求正确地形成语法。
  • @kartik:不,这与语法无关。这是关于后增量和左值的语义。这就是为什么我给出了一个更简单的问题版本。

标签: c pointers void-pointers


【解决方案1】:

这个:

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。也许从函数中返回它是有意义的,但你没有指定。

【讨论】:

    【解决方案2】:

    那一行应该改写为

    *( (unsigned char*)(buf) + sizeof(some_struct) + i) = ptr[i];
    

    确实,一个更容易理解的实现:

    memcpy(buf + sizeof(some_struct), ptr, MESSAGE_LTH);
    

    没有循环。

    【讨论】:

    • 谢谢,但我希望缓冲区在附加用户名后立即指向下一个位置,以便我可以附加更多字段。
    • 复制准备好后增加指针。保持代码简单明了让生活更轻松。
    • 只是出于好奇,如何使用 ++ 运算符获得相同的结果?
    • *( (unsigned char*)(buf++) + sizeof(some_struct)) = ptr[i];
    • memcpy 版本在 LHS 中没有 i
    猜你喜欢
    • 2015-10-05
    • 2016-12-01
    • 2015-07-03
    • 2021-12-03
    • 2010-10-25
    • 2016-08-29
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多