任何人都可以帮我理解这个程序中的typedef吗?

Dee*_*pak 4 c typedef

它只是一个简单的C程序,我不明白这一点是:当我们写的时候

typedef int RowArray[COLS];    
Run Code Online (Sandbox Code Playgroud)

我认为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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

typedef int new_thing;

func(new_thing x)    //here i assume it works as (int x) as we did typedef int new_thing earlier.
Run Code Online (Sandbox Code Playgroud)

但是当大括号开始时

{
    float new_thing; //so what happens here exactly (float int;) ???
    new_thing = x;   // and here too int = x; ????
}
Run Code Online (Sandbox Code Playgroud)

很明显,我错过了一些东西并错误地解释了它.感谢帮助.

Yu *_*Hao 7

你是混淆typedef#define.预处理器#define是简单文本替换的那个.

typedef,在另一方面,是不是预处理器的一部分,但语法像关键字extern,static等它提供了某种类型的新名称.

typedef int RowArray[COLS]; 
Run Code Online (Sandbox Code Playgroud)

RowArray定义int具有COLS元素的数组类型.所以

RowArray *rptr; 
Run Code Online (Sandbox Code Playgroud)

rptr是一个指向intCOLS元素的数组的指针.