有人可以向我解释一下这个函数的语法吗?其中SYS_fork是一个常量,sys_fork是一个函数。
static int (*syscalls[])(void) = {
[SYS_fork] sys_fork,
[SYS_exit] sys_exit,
[SYS_wait] sys_wait,
[SYS_pipe] sys_pipe,
[SYS_read] sys_read,
[SYS_kill] sys_kill,
[SYS_exec] sys_exec,
};
谢谢!
答案 0 :(得分:26)
您刚刚遇到designated initializers的使用。它们存在于C99中,也可作为GCC扩展,在Linux内核代码(以及其他)中广泛使用。
来自文档:
在ISO C99中,您可以按任意顺序给出[数组]的元素,指定它们适用的数组索引或结构字段名称,GNU C也允许它作为C90模式的扩展。 [...]
要指定数组索引,请在元素值之前写入“[index] =”。例如,
int a[6] = { [4] = 29, [2] = 15 };
相当于:
int a[6] = { 0, 0, 15, 0, 29, 0 };
[...]
自GCC 2.5以来已经过时的替代语法已经过时,但GCC仍然接受的是在元素值之前写'[index]',没有'='。
用简单的英语syscalls
is a static array of pointer to function taking void
and returning int
。数组索引是常量,它们的相关值是相应的函数地址。
答案 1 :(得分:0)
运行下面的代码你就会知道发生了什么:
#include <stdio.h>
void function_1(char *);
void function_2(char *);
void function_3(char *);
void function_4(char *);
#define func_1 1
#define func_2 2
#define func_3 3
#define func_4 4
void (*functab[])(char *) = { // pay attention to the order
[func_2] function_2,
[func_3] function_3,
[func_1] function_1,
[func_4] function_4
};
int main()
{
int n;
printf("%s","Which of the three functions do you want call (1,2, 3 or 4)?\n");
scanf("%d", &n);
// The following two calling methods have the same result
(*functab[n]) ("print 'Hello, world'"); // call function by way of the function name of function_n
functab[n] ("print 'Hello, world'"); // call function by way of the function pointer which point to function_n
return 0;
}
void function_1( char *s) { printf("function_1 %s\n", s); }
void function_2( char *s) { printf("function_2 %s\n", s); }
void function_3( char *s) { printf("function_3 %s\n", s); }
void function_4( char *s) { printf("function_4 %s\n", s); }
结果:
Which of the three functions do you want call (1,2, 3 or 4)?
1
function_1 print 'Hello, world'
function_1 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
2
function_2 print 'Hello, world'
function_2 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
3
function_3 print 'Hello, world'
function_3 print 'Hello, world'
Which of the three functions do you want call (1,2, 3 or 4)?
4
function_4 print 'Hello, world'
function_4 print 'Hello, world'