简体   繁体   English

在C语言中:指向函数时使用void和int关键字

[英]In C: using void and int keywords while pointing to functions

I am trying to do a program where the function is pointed by a pointer. 我正在尝试编写一个函数,该函数由指针指向。 It goes as follows:- 它如下:

This is the first program which uses "void" return type. 这是第一个使用“ void”返回类型的程序。

#include<stdio.h>
#include<conio.h>
void CharPrint(char *ptr);
main()
{
    char *str="Hello World";
    void (*ptr1)(char *ptr);
    ptr1=CharPrint;
    if((*ptr1)(str))
        printf("Done");
    return 0;
}
void CharPrint(char *ptr)
{
    printf("%s\n",ptr);
}

It throws many errors. 它引发许多错误。 They are:- 他们是:-

在此处输入图片说明

The second program is as follows:- 第二个程序如下:

#include<stdio.h>
#include<conio.h>
int CharPrint(char *ptr);
main()
{
    char *str="Hello World";
    int (*ptr1)(char *ptr);
    ptr1=CharPrint;
    if((*ptr1)(str))
        printf("Done");
    return 0;
}
int CharPrint(char *ptr)
{
    printf("%s\n",ptr);
    return 0;
}

This program runs without any hiccup. 该程序运行没有任何打h。

The output is:- 输出为:-

在此处输入图片说明

My problem is that in the first output, why is it showing " Not an allowed type in function main " on line 9. The other lines are also arising doubts but this line is bugging me the most. 我的问题是,在第一个输出中,为什么它在第9行上显示“函数main中的不允许类型”。其他几行也引起了疑问,但此行最困扰我。 Any help? 有什么帮助吗?

Your first function does not return anything. 您的第一个函数不返回任何内容。 Thus, you cannot test if((*ptr1)(str)) . 因此,您无法测试if((*ptr1)(str))

void (*ptr1)(char *ptr);
ptr1=CharPrint;
if((*ptr1)(str))
    printf("Done");

What is the if testing if the return value is void ? if测试返回值是否为void怎么办? Just change the last two lines to: 只需将最后两行更改为:

((*ptr1)(str));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM