这种对 void 指针的尊重正确吗?

问题描述 投票:0回答:1

我在谷歌上查找并偶然发现了这篇文章,但这并不能完全回答我的问题(或者也许我只是无法到达那里)。 取消引用空指针

我正在尝试创建一个函数来设置未知类型的指针。基本上:

struct x{
type *links[LINK_SIZE];
// other data
};
somefunc(void *x, void *y void* z)

这里 x 是一个指向 struct x 的指针,但作为 void 指针传递。我想取消引用 void * 指针以访问其第一个元素,即链接。据我所知,C 中的所有指针都具有相同的大小(不确定!但至少对于 gcc 编译器而言)。所以,理论上,它应该可以工作,并且可以与我的 gcc 编译器一起工作。基本上,如果您取消引用结构体的指针,您将获得该结构体中的第一个元素。我想知道这是否是未定义的行为?

#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
typedef struct e{
    struct e *links[2];
    int a;
}e;

void somefunc(void *x, void *y, void *z) {
    void **epl = (void **)x;
    epl[0] = y; 
// also see how I am accessing it like a normal array, is this even possible for void pointers?
    epl[1] = z;
}

int main(void) {
    e e1 = (e){{NULL, NULL}, 1};
    e e2 = (e){{NULL, NULL}, 2};
    e e3 = (e){{NULL, NULL}, 3};
    somefunc(&e1, &e2, &e3);    
    printf("%d\n", e1.links[0]->a);
    printf("%d\n", e1.links[1]->a);
    printf("%d\n", e1.a);
    return 0;
}

编辑: 实际的根本问题基本上是说我有两种不同的结构。

typedef struct e{
    struct e *links[2];
    int a;
}e;

typedef struct f{
    struct f *links[2];
    float a;
}f;

我想要 1 个函数能够更新两个结构的

links
,而不是有两个函数,一个转换为
f *
,另一个转换为
e *

c pointers
1个回答
0
投票

假设您有几个具有相似结构的结构,即:

typedef struct e {
    struct e *links[2];
    int a;
} e;
typedef struct f {
    struct f *links[2];
    float a;
} f;

并且您希望一个函数能够与这两个函数一起使用,这可能是类似函数的宏的情况:

#define somefunc(x, y, z)\
  do {\
      (x).links[0] = (y);\
      (x).links[1] = (z);\
  } while (0)

你可以这样称呼:

somefunc(e1, e2, e3);    
somefunc(f1, f2, f3);    
© www.soinside.com 2019 - 2024. All rights reserved.