函数指针在C中与struct无关

时间:2022-09-06 11:27:30

I have the following code:

我有以下代码:

#include <stdio.h>
#include <stdlib.h>

struct Book {
    char title[50];
    char author[50];
    char subject[100];
    int numPages;
    int numBooks;

    int (*p) (int *, int *);
};

int sum (int *a, int *b) {
    return *a + *b;
}

int main() {
    struct Book var;
    var.numPages = 7;
    var.numBooks = 9;
    int allPages = (*var.p) (&var.numPages, &var.numBooks);

    printf("%d\n", allPages);
    return (EXIT_SUCCESS);
}

I trying to use function in struct but my program have no result, no warning although I used -Wall, -Wextra. I'm a newbie. Hope everybody help.

我试图在struct中使用函数,但我的程序没有结果,没有警告,虽然我使用-Wall,-Wextra。我是新手。希望大家帮忙。

2 个解决方案

#1


2  

var.p is not initialized (meaning it almost certainly doesn't refer to a valid function), creating undefined behavior. Use var.p = sum; to initialize it before the function call.

var.p未初始化(意味着它几乎肯定不会引用有效函数),从而创建未定义的行为。使用var.p = sum;在函数调用之前初始化它。

#2


0  

In your code you should first assign a function to a pointer and then by using a pointer call a function. for this your code should be

在您的代码中,您应首先将函数分配给指针,然后使用指针调用函数。为此您的代码应该是

 int main()

  {
   struct Book var;
   var.numPages = 7;
   var.numBooks = 9;
   var.p=sum;

    int allPages =var.p(&var.numPages, &var.numBooks);

     printf("%d\n", allPages);
     return (EXIT_SUCCESS);
  }

for further information you can refer

有关详细信息,请参阅

C - function inside struct

C - struct内部的函数

#1


2  

var.p is not initialized (meaning it almost certainly doesn't refer to a valid function), creating undefined behavior. Use var.p = sum; to initialize it before the function call.

var.p未初始化(意味着它几乎肯定不会引用有效函数),从而创建未定义的行为。使用var.p = sum;在函数调用之前初始化它。

#2


0  

In your code you should first assign a function to a pointer and then by using a pointer call a function. for this your code should be

在您的代码中,您应首先将函数分配给指针,然后使用指针调用函数。为此您的代码应该是

 int main()

  {
   struct Book var;
   var.numPages = 7;
   var.numBooks = 9;
   var.p=sum;

    int allPages =var.p(&var.numPages, &var.numBooks);

     printf("%d\n", allPages);
     return (EXIT_SUCCESS);
  }

for further information you can refer

有关详细信息,请参阅

C - function inside struct

C - struct内部的函数