【问题标题】:C structure that ends with an asterisk以星号结尾的 C 结构
【发布时间】:2018-06-04 17:55:37
【问题描述】:

我在看这个example,发现里面有声明

struct edge
{
      int x;
      int y;
      int weight;
      struct edge *link;
}*front = NULL;

这实际上是什么意思?是否可以创建一个结构,它也是一个名称为front的指针,它为NULL...?

【问题讨论】:

  • 语法与int* x; 相同。只是有一个struct类型而不是int
  • A struct 只是另一种类型的变量。所以,类似于int *a = NULL;,可以创建为struct name{...} *tag = NULL;

标签: c pointers struct


【解决方案1】:

结构体只是另一种 C 类型,因此,它用于定义的变量可以创建为普通实例或指针:

int a, *pA=NULL; //normal instance, pointer instance

struct edge
{
      int x;
      int y;
      int weight;
      struct edge *link;
}sEdge, *front = NULL; //normal instance, pointer instance

并且,与任何指针变量一样,需要先将其指向拥有的内存,然后才能安全使用:(示例)

int main(void)
{

    // both variable types are handled the same way... 

    pA = &a; //point pointer variable to normal instance of `int a`
    front = &sEdge;//point pointer `front` to instance of 'struct edge'

    //allocate memory, resulting in assigned address with associated memory.
    pA = malloc(sizeof(*pA));
    front = malloc(sizeof(*front)); 
    ...

编辑 在 cmets 中回答问题:
这个小例子不会引发错误或警告。 (在上面编辑您的问题,或者更好的是,发布另一个问题,显示您所看到的详细信息。)

struct edge
{
      int x;
      int y;
      int weight;
      struct edge *link;
}*front = '\0';

int main(void)
{
    struct edge tree[10];

    return 0;
}

【讨论】:

  • 在 main() 方法中,同一程序声明了 'struct edge tree[10];'我的编译器在其中抛出错误“数组类型的元素类型不完整”。那么如何初始化这个变量呢?
  • 为此,我们需要查看更多您的代码; minimal example from what you've saidthe code shown in the linked blog post 都不会发生这种情况。
  • @VassilisDe - 我已经包含了您在上面的编辑中所描述的内容,当我使用C99 编译器规则构建时,我没有收到编译器警告或错误。
  • 也许我做的不对……我为接口和函数实现保留了单独的文件。我从主文件中排除了声明结构的头文件,但编译器现在抱怨结构声明被调用了两次
  • @VassilisDe - 警告是否类似于:multiply defined symbol?如果是这样,您确实在不止一个地方定义了它。查找并使用extern 修饰符来修改变量的范围。 static 也可以根据您需要完成的任务来使用。
【解决方案2】:

它是一个指向结构的指针和一个名为struct edge的新类型的声明

【讨论】:

  • 这有点令人困惑,或者严格来说是错误的,因为它很明显也是一个名为struct edge的新类型的声明。
  • 我认为这是“给定的”@unwind,正如反对票所暗示的那样,我错了。对不起。我现在更新了答案,希望它有所改善,谢谢!
【解决方案3】:

当你写的时候,也许这会让你更清楚:

struct edge
{
      int x;
      int y;
      int weight;
      struct edge *link;
};

您是说:我正在创建 struct edge,我将通过键入以下内容来定义此结构的对象:

struct edge edgeObject;

但是当你写的时候:

struct edge
{
      int x;
      int y;
      int weight;
      struct edge *link;
} edgeObject;

您是说:我正在创建结构边缘,同时我正在定义类型为struct edge 的edgeObject。 这允许您直接使用该对象,因为它已经定义:

edgeObject.x = 0;

所以回到你的例子,你是说:我正在创建结构边缘,同时我正在定义指向该结构 front 的指针,该指针设置为 NULL。

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 2011-05-20
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2020-11-09
    • 2020-06-14
    相关资源
    最近更新 更多