将函数指针作为参数传递时出错
Error while Passing function pointer as parameter
我有一个程序可以调用库中的函数。函数的参数是一个函数指针。
Helloworld.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "helloworld.h"
struct data_buffer
{
char name[10];
}data;
int main()
{
int result;
int (*func_pointer)(&data_buffer); //function pointer which takes structure as parameter
result=send_data(func_ponter); //error
func_pointer(&data_buffer); //call the SPI write
}
helloworld.h
#ifndef HELLOWORLD_H
#define HELLOWORLD_H
/* Some cross-platform definitions generated by autotools */
#if HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
/*
* Example function
*/
struct data_buffer;
extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct
#endif
libexample.c
#include<stdio.h>
#include<stdlib.h>
int send_data(int (*func_pointer)(&data_buffer)) //error
{
func_pointer=spi_write(); // assigning the function pointer to SPI WRITE function
return;
}
所以我的项目目标是将函数指针作为参数发送给 send_data 函数。在库程序中,必须将函数指针分配给 spi_write() 函数,然后才能在 Helloworld 程序中借助函数指针调用 SPI_Write。
extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct
函数的参数必须是类型。类型使用 *
表示它是一个指针。所以 &data_buffer
在声明中是不正确的。
另请注意,在 C 中,与 C++ 不同,结构名称不是类型,您需要将其与关键字 struct
组合(或使用 typedef)。所以使用:
extern int send_data(int (*func_pointer)(struct data_buffer *));
我有一个程序可以调用库中的函数。函数的参数是一个函数指针。
Helloworld.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "helloworld.h"
struct data_buffer
{
char name[10];
}data;
int main()
{
int result;
int (*func_pointer)(&data_buffer); //function pointer which takes structure as parameter
result=send_data(func_ponter); //error
func_pointer(&data_buffer); //call the SPI write
}
helloworld.h
#ifndef HELLOWORLD_H
#define HELLOWORLD_H
/* Some cross-platform definitions generated by autotools */
#if HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
/*
* Example function
*/
struct data_buffer;
extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct
#endif
libexample.c
#include<stdio.h>
#include<stdlib.h>
int send_data(int (*func_pointer)(&data_buffer)) //error
{
func_pointer=spi_write(); // assigning the function pointer to SPI WRITE function
return;
}
所以我的项目目标是将函数指针作为参数发送给 send_data 函数。在库程序中,必须将函数指针分配给 spi_write() 函数,然后才能在 Helloworld 程序中借助函数指针调用 SPI_Write。
extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct
函数的参数必须是类型。类型使用 *
表示它是一个指针。所以 &data_buffer
在声明中是不正确的。
另请注意,在 C 中,与 C++ 不同,结构名称不是类型,您需要将其与关键字 struct
组合(或使用 typedef)。所以使用:
extern int send_data(int (*func_pointer)(struct data_buffer *));