【发布时间】: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 定义的类型相同。