您的位置:首页 > 编程语言 > PHP开发

typedef 与函数指针

2011-08-17 09:51 134 查看
 

typedef double *Dp;  
分析:
去掉typedef  ,得到正常变量声明=> double *Dp;
变量Dp的类型为double*,即pointer to double;
=> "typedef double *Dp"中Dp是类型double*的一个typedef-name。
Dp    dptr; <=> dptr是一个pointer to double的变量
 
[例3]
typedef int* Func(int);
分析:
去掉typedef  ,得到正常变量声明=> int* Func(int);
变量Func的类型为一个函数标识符,该函数返回值类型为int*,参数类型为int;
=> "typedef int* Func(int)"中Func是函数类型(函数返回值类型为int*,参数类型为int)的一个typedef-name。
Func    *fptr; <=> fptr是一个pointer to function with one int parameter, returning a pointer to int
Func     f;   这样的声明意义就不大了。
 
[例4]
typedef int (*PFunc)(int);
分析:
去掉typedef  ,得到正常变量声明=> int (*PFunc)(int);
变量PFunc的类型为一个函数指针,指向的返回值类型为int,参数类型为int的函数原型;
=> "typedef int (*PFunc)(int)"中PFunc是函数指针类型(该指针类型指向返回值类型为int,参数类型为int的函数)的一个typedef-name。
PFunc     fptr; <=> fptr是一个pointer to function with one int parameter, returning int

#include "iostream"

using namespace std;

int add(int a,int b){

return (a+b);

}

typedef int (* func)(int ,int ) ;

void main(){

func f = add;

int n = f(1,2);

cout << n << endl;

}

[例5]
typedef    int   A[5];
分析:
去掉typedef ,得到正常变量声明 => int   A[5];
变量A的类型为一个含有5个元素的整型数组;
=> "typedef    int   A[5]"中A是含有5个元素的数组类型的一个typedef-name。
A   a = {3, 4, 5, 7, 8};
A   b = { 3, 4, 5, 7, 8, 9}; /* 会给出Warning: excess elements in array initializer */
[例6]
typedef    int   (*A)[5]; (注意与typedef    int*    A[5]; 区分)
分析:
去掉typedef ,得到正常变量声明 => int   (*A)[5];
变量A的类型为pointer to an array with 5 int elements;
=> "typedef    int   (*A)[5]"中A是"pointer to an array with 5 int elements"的一个typedef-name。
int   c[5] = {3, 4, 5, 7, 8};  
A    a = &c;
printf("%d\n", (*a)[0]); /* output: 3 */
如果这样赋值:
int   c[6] = {3, 4, 5, 7, 8, 9};  
A    a = &c; /* 会有Warning: initialization from incompatible pointer type */
 
1、"ISOIEC-98991999(E)--Programming Languages--C"之Page 123;
2、C语言参考手册(中文版) 之 Page 119

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息