【问题标题】:Can anyone help me to understand typedef in this program?谁能帮我理解这个程序中的 typedef 吗?
【发布时间】:2014-06-23 06:30:00
【问题描述】:

它是一个简单的 C 程序,我唯一不明白的是:当我们编写时

typedef int RowArray[COLS];    

我认为 typedef 的工作方式是从 typedef 到最后一个单词被“;”之前的最后一个单词替换。所以在这必须有一个类似 typedef int RowArray[COLS] X;然后 X *rptr;

但在这里我无法理解。如果可能的话,你能给我一个关于 typedef 的材料的链接,其中解释了这种情况。

#include <stdio.h>
#include <stdlib.h>
#define COLS 5

typedef int RowArray[COLS];  // use of typedef 
RowArray *rptr;              // here dont we have to do RowArray[COLS] *rptr;

int main()
{
  int nrows = 10;
  int row, col;
  rptr = malloc(nrows * COLS * sizeof(int));

  for(row=0; row < nrows; row++)
    {
      for(col=0; col < COLS; col++)
    {
      rptr[row][col] = 17;
    }
    }

  for(row=0; row<nrows; row++)
    {
      for(col=0; col<COLS; col++)
    {
      printf("%d  ", rptr[row][col]);
    }
      printf("\n");
    }
  return 0;
}

explanation of typedef 从上面的链接中,我了解了我在问题中发布的示例代码中 typedef 的工作。但是在链接中进一步阅读它显示了 typedef 的另一个示例。

//To re-use a name already declared as a typedef, its declaration must include at least one type specifier, which removes any ambiguity:

typedef int new_thing;
func(new_thing x){
        float new_thing;
        new_thing = x;
}

现在,如果有人可以解释这里发生的事情,因为这会让我更加困惑。 和第一行一样

typedef int new_thing;

func(new_thing x)    //here i assume it works as (int x) as we did typedef int new_thing earlier.

但是当大括号开始时

{
    float new_thing; //so what happens here exactly (float int;) ???
    new_thing = x;   // and here too int = x; ????
}

很明显我遗漏了一些东西并错误地解释了它。 感谢您的帮助。

【问题讨论】:

  • 这个问题可能是重复的......我在某处看到了类似的东西......如果我没记错的话,投票最多的答案是这样的:“Typedef 没有出现在 C 的第一个版本中,他们必须保留旧语法以实现兼容性......”然后说为什么 typedef 的工作方式与大多数人期望它在数组上的工作方式不同
  • 要理解typedef,想象一下同样的声明,但去掉了typedef这个词。那么你要在那里声明的变量的类型,与 typedef 定义的类型相同。

标签: c typedef


【解决方案1】:

您将typedef#define 混淆了。预处理器#define 是一个简单的文本替换。

另一方面,typedef 不是预处理器的一部分,但在语法上类似于关键字externstatic 等。它为特定类型赋予了新名称。

typedef int RowArray[COLS]; 

RowArray 定义了一个带有COLS 元素的int 数组类型。所以

RowArray *rptr; 

rptr 是指向带有COLS 元素的int 数组的指针。

【讨论】:

    【解决方案2】:

    虽然 typedef 被认为是一个存储类,但实际上并非如此。它允许您为可以以其他方式声明的类型引入同义词。如本例所示,新名称将等同于您想要的类型。

    typedef int aaa, bbb, ccc;
    typedef int ar[15], arr[9][6];
    typedef char c, *cp, carr[100];
    
    /* now declare some objects */
    
    /* all ints */
    aaa     int1;
    bbb     int2;
    ccc     int3;
    
    ar      yyy;    /* array of 15 ints */
    arr     xxx;    /* 9*6 array of int */
    
    c       ch;     /* a char */
    cp      pnt;    /* pointer to char */
    carr    chry;   /* array of 100 char */
    

    使用 typedef 的一般规则是写出一个声明,就好像你在声明你想要的类型的变量一样。在声明将引入具有特定类型的名称的情况下,使用 typedef 作为前缀意味着,您无需声明变量,而是声明新的类型名称。然后可以将这些新类型名称用作新类型变量声明的前缀。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多