c - 结构内部的结构 : to point or not to point?

标签 c pointers struct

我想了解在引用另一个 struct 内的 struct 时使用指针和值之间的区别。

我的意思是,我可以有这两个声明:

struct foo {
    int bar;
};

struct fred {
    struct foo  barney;
    struct foo *wilma;
}

似乎我可以从barneywilma条目获得相同的行为,只要我在访问时相应地取消引用他们。 barney 案例直观上感觉“错误”,但我无法说出原因。

我只是依赖于一些 C 未定义的行为吗?如果不是,选择一种风格而不是另一种风格的原因是什么?

以下代码显示了我如何得出两个用例是等效的结论; clanggcc 都没有提示任何事情。

#include <stdio.h>
#include <stdlib.h>

struct a_number {
    int i;
};

struct s_w_ptr {
    struct a_number *n;
};

struct s_w_val {
    struct a_number n;
};

void store_via_ptr(struct s_w_ptr *swp, struct s_w_val *swv) {
    struct a_number *i = malloc(sizeof(i));
    i->i   =  1;
    swp->n =  i;
    swv->n = *i;
}

void store_via_val(struct s_w_ptr *swp, struct s_w_val *swv) {
    struct a_number j;
    j.i    =  2;
    swp->n = &j;
    swv->n =  j;
}

int main(void) {

    struct s_w_ptr *swp = malloc(sizeof(swp));
    struct s_w_val *swv = malloc(sizeof(swv));

    store_via_ptr(swp, swv);
    printf("p: %d | v: %d\n", swp->n->i, swv->n.i);

    store_via_val(swp, swv);
    printf("p: %d | v: %d\n", swp->n->i, swv->n.i);
}

最佳答案

在结构体中同时拥有结构体成员和在结构体中拥有指向结构体的指针是完全有效的。它们的使用方式必须不同,但都是合法的。

为什么结构体中有结构体?

一个原因是将事物组合在一起。例如:

struct car
{
    struct motor motor;  // a struct with several members describing the motor
    struct wheel wheel;  // a struct with several members describing the wheels
    ...
}

struct car myCar = {....initializer...};

myCar.wheel = SomeOtherWheelModel;  // Replace wheels in a single assign
myCar.wheel.pressure = 2.1;         // Change a single wheel member

为什么结构体中有一个结构体指针?

一个非常明显的原因是,通过使用 N 倍结构大小的动态分配,可以将其用作 N 个结构的数组。

另一个典型的例子是链表,其中有一个指向与包含该指针的结构类型相同的结构的指针。

关于c - 结构内部的结构 : to point or not to point?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69028188/

相关文章:

c++ - 指向数组第 [-1] 个索引的指针

c - 成员为指针的结构数组

c - 带有指向结构节点的指针的动态数组

c - 使用 pthread_create 时结构会丢失对变量的跟踪

c - 第一个 C 编译器是如何编写的?

从 C 程序编译和构建 C 文件

c - 如何在 Windows 上的 C 程序中使用未定义的句柄之一?

在数组中创建不同的随机数

java - JNA : Pointer to array of Struct : Invalid Pointer

python - 从文件中读取结构体数组