C 中的安全铸造

发布于 2024-11-08 22:32:42 字数 228 浏览 0 评论 0原文

大家好,我有这段代码:

void writer(void* param){
    if(NULL == param){
        return;
    }
    param = (param_t*)param;
...
}

它是否安全,参数来自 param_t* 类型,但是当我在函数中使用它时,每次进行转换时我都感到恶心,有人有另一个优雅的解决方案吗?提前致谢

hello everyone I have this snippet of the code:

void writer(void* param){
    if(NULL == param){
        return;
    }
    param = (param_t*)param;
...
}

is it safe code, or not, param is from type param_t*, but I'm sick doing every time casting when I use it in function, do Somebody have another elegant solution? thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岁月静好 2024-11-15 22:32:42

这是一个奇怪的禁止操作。

当您定义函数时,您说参数的类型为 void*
然后,通过强制转换,将其显式转换为 param_t*
编译器通过赋值隐式地将 param_t* 转换为 void*

你需要另一个变量

void writer(void *param) {
    param_t *internal_param;

    if (NULL == param) return;
    internal_param = param;
    /* ... */
}

That is a strange no-op.

When you define the function you say param is of type void*.
Then, with the cast, you explicitly convert it to param_t*
And the compiler implicitly converts that param_t* to void* with the assignment.

You need another variable

void writer(void *param) {
    param_t *internal_param;

    if (NULL == param) return;
    internal_param = param;
    /* ... */
}
別甾虛僞 2024-11-15 22:32:42

即使指针值为 NULL,赋值中的(隐式)强制转换也是安全的,因此无需推迟它。你可以这样做:

void writer(void* param)
{
  param_t* myparam = param;

  if (myparam == NULL)
    return;

  ...
}

The (implicit) cast in the assignment is safe even if the pointer value is NULL, so there's no need to defer it. You could do this:

void writer(void* param)
{
  param_t* myparam = param;

  if (myparam == NULL)
    return;

  ...
}
趴在窗边数星星i 2024-11-15 22:32:42

您不必将 void* 转换为 C 中的另一种指针类型。

所以只需执行以下操作:(

void writer(void* param){
   param_t *myparam;
    if(NULL == param){
        return;
    }
    myparam = param;
...
}

但是为什么您要使用 void* 作为参数呢?)

You do not have to cast a void* to another pointer type in C.

So just do:

void writer(void* param){
   param_t *myparam;
    if(NULL == param){
        return;
    }
    myparam = param;
...
}

(But why are you using a void* for the argument anyway?)

池予 2024-11-15 22:32:42

显而易见的解决方案是避免使用 void * 并使用 param_t * 代替,如下所示:

void writer(param_t * param)
{
  if (param == NULL)
  {
    return;
  }

  ...
}

如果您知道,您可以删除 NULL 测试从未使用 NULL 指针调用。或者,您可以将其替换为 assert(param != NULL)

The obvious solution is to avoid using void * and use param_t * instead, as in:

void writer(param_t * param)
{
  if (param == NULL)
  {
    return;
  }

  ...
}

You could drop the NULL test if you know that it's never called with a NULL pointer. Alternatively, you could replace it with assert(param != NULL).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文