Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么函数指针的typedef不同于常规的typedef?_C_Pointers_Function Pointers_Typedef - Fatal编程技术网

C 为什么函数指针的typedef不同于常规的typedef?

C 为什么函数指针的typedef不同于常规的typedef?,c,pointers,function-pointers,typedef,C,Pointers,Function Pointers,Typedef,typedef通常的工作方式如下:typedef。但是函数指针的typedef似乎有不同的结构:typedefint(*fn)(char*,char*)-没有类型别名,只有一个函数签名 下面是示例代码: #include <stdio.h> typedef void (*callback)(int); void range(int start, int stop, callback cb) { int i; for (i = start; i < stop;

typedef
通常的工作方式如下:
typedef
。但是函数指针的typedef似乎有不同的结构:
typedefint(*fn)(char*,char*)-没有类型别名,只有一个函数签名

下面是示例代码:

#include <stdio.h>

typedef void (*callback)(int);

void range(int start, int stop, callback cb) {
    int i;
    for (i = start; i < stop; i++) {
        (*cb)(i);
    }
}

void printer(int i) {
    printf("%d\n", i);
}

main(int argc, int *argv[])
{
    if (argc < 3) {
        printf("Provide 2 arguments - start and stop!");
    }

    range(atoi(argv[1]), atoi(argv[2]), printer);
}
#包括
typedef void(*回调)(int);
无效范围(整数开始、整数停止、回调cb){
int i;
对于(i=开始;i<停止;i++){
(*cb)(i);
}
}
无效打印机(int i){
printf(“%d\n”,i);
}
main(int-argc,int*argv[])
{
如果(argc<3){
printf(“提供2个参数-开始和停止!”);
}
范围(atoi(argv[1])、atoi(argv[2])、打印机);
}

那么-为什么函数指针的
typedef
s不同呢?

使用
typedef
定义函数指针类型的语法与定义函数指针的语法相同

int (*fn)(char *, char *);
fn
定义为指向函数的指针

typedef int (*fn)(char *, char *);

fn
定义为指向函数的指针的类型
..

其工作原理相同。你只需要用稍微不同的方式来看待它
typedef
定义您自己的类型名称,方法是将它放在变量标识符不带
typedef
的地方。所以

typedef int (*fn)(char *, char *);
uint8_t foo;
变成

typedef uint8_t footype;
footype foo;

edit:所以“R Sahu”的速度要快一点,看看他的例子,看看他在函数指针上应用的相同原理。

C声明语法比
类型标识符
复杂得多,例如

int (*fn)(char *, char *);
T (*ap)[N];             // ap is a pointer to an N-element array
T *(*f())();            // f is a function returning a pointer to
                        // a function returning a pointer to T
在语法上,
typedef
被视为存储类说明符,如
static
extern
。因此,您可以将
typedef
添加到上述每一项中,给出

typedef T (*ap)[N];     // ap is an alias for type "pointer to N-element array
typedef T *(*f())();    // f is an alias for type "function returning
                        // pointer to function returning pointer to T"

你能给我一个标准的参考吗?它在。(关键短语:“以6.7.5中描述的方式”)外观,
typedef void fv(int),(*pfv)(int)-注意,第二个函数声明没有返回类型。因此,
typedef
void
type与以下函数签名相关联。因此,您可以编写
typedef void fn1(int),(*fnptr1)(int),fn2(char*)这只是逗号在声明中的正常工作方式。删除
typedef
,看看它是什么意思。顺便说一句,这是一个完美的例子,展示了C声明如何看起来非常模糊。这可能就是存在的原因;)[注意,本网站不理解逗号…哈哈]这与声明函数指针变量的方式相同。