这个声明"int(*ptr[3])();"是什么意思?

What does this declaration means "int(*ptr[3])();"?

本文关键字:是什么 意思 ptr 声明 int      更新时间:2023-10-16

整个代码:

#include<stdio.h>    
 aaa(){ 
    printf("hi");  
 }  
 bbb(){  
    printf("hello");  
 }  
 ccc(){ 
    printf("ccc");  
 }  
int main(){  
     int(*ptr[3])(); 
     ptr[0]=aaa;  
     ptr[1]=bbb;  
     ptr[3]=ccc;   
     ptr[3]();   
}   

输出将为"再见"。
我从看到代码中看到int(*ptr[3])()是某种与 int 相关的数组声明,它也看起来像函数调用。在下面的代码行中,函数名被分配给数组,数组片段可用于函数调用。有人可以解释一下,声明是什么以及函数调用是如何进行的吗?

当你遇到这样的类型时,你可以使用cdecl工具来解码它:

$ cdecl explain "int (*p[3])()"
declare p as array 3 of pointer to function returning int
$

请注意,ptr是 cdecl 的保留字,您只需将变量重命名为更基本的名称......

------编辑------

请注意,空参数列表在 C 或 C++ 中的含义不同。在 C 中,这意味着具有未知数量参数的函数(没有参数的 C 函数必须声明为 f(void) )。在C++中,这意味着一个没有参数的函数。

它将ptr声明为一个由 3 个类型为 int(*)() 的元素组成的数组,这是一个指向类型 int() 的指针,这是一个返回 int 的零参数函数。

int (*ptr[3])() 是一个由 3 个指向返回 int 的函数的指针组成的数组。

更清楚一点,这意味着它是一个函数指针数组。数组有容纳其中 3 个的空间,函数应返回 int。


示例代码的其他一些问题

代码有一些问题,所以我去整理了一下。

在数组中越界分配是未定义的行为

test.c:30:3: warning: array index 3 is past the end of the array (which contains 3
elements) [-Warray-bounds]
ptr[3] = ccc;
^   ~
test.c:23:3: note: array 'ptr' declared here
int (*ptr[3])();

清理代码:

#include <stdio.h>
/* Missing function prototypes
 * For C a function taking no arguments should have void for its argument
 * For C++ void can be skipped
 */
int aaa(void);
int bbb(void);
int ccc(void);
/* The function should be declared with type specifier, although it is assumed
 * by default to return int.
 */
int aaa(void) {
  /* Unless this print statement is going to be part of more output, you should
   * return a newline
   */
  printf("hin");
  /* As this function is meant to return an int, we will return 0*/
  return 0;
}
int bbb(void) {
  printf("hellon");
  return 0;
}
int ccc(void) {
  printf("cccn");
  return 0;
}
int main(void) {
  int (*ptr[3])();
  ptr[0] = aaa;
  ptr[1] = bbb;
  /* Now assigning to valid ptr[2] and not out of bounds ptr[3] */
  ptr[2] = ccc;
  ptr[2]();
}

它只是意味着一个指向函数的 3 个指针数组,即 aaa()、bbb() 和 ccc()。 :)

简单来说,一个由 3 个函数指针组成的数组。

我想

ptr[3] = ccc;在这里是错误的......它就像 ABW - 写出数组的界限。 应该是... ptr[2] = ccc;

该声明意味着某人没有清晰地思考。如果展开会简单得多:

typedef int (*fptr)();
fptr ptr[3];