[英]how to use pointers to functions?
for exp : this program isn't working to me.. can anyone explian to me how to use correctly a way to use in this program pointers to functions the program gives me runtime error 对于exp:这个程序对我不起作用..任何人都可以向我展示如何使用正确的方法在这个程序中使用指针函数程序给我运行时错误
the program should be generic and returns the size of any given array 程序应该是通用的,并返回任何给定数组的大小
#include<stdio.h>
#include<string.h>
int ReturnSize_INT(void *a)
{
a = (int*)a;
int count = 0 ;
int *p = (int*)a;
while(p != NULL)
{
count++;
p++;
}
return count;
}
int ReturnSize_char(void *a)
{
a = (char*)a;
int count = 0 ;
char *p = (char*)a;
while(p != NULL)
{
count++;
p++;
}
return count;
}
int ReturnSize_float(void *a)
{
a = (int*)a;
int count = 0 ;
float *p = (float*)a;
while(p != NULL)
{
count++;
p++;
}
return count;
}
int main()
{
int a [] = {1,2,5,7,8};
char b[]={'a','b','c','\0'};
float c [] = {2.75,5.25,7.27,4.25};
int (*ReturnSize)(void *e);
ReturnSize = ReturnSize_INT;
printf("%d",ReturnSize(&a));
return 0;
}
Pass a
to the function - not &a
. 经过a
到功能-不&a
。 The name of the array is a pointer to the start of the array. 数组的名称是指向数组开头的指针。
printf("%d",ReturnSize(a));
Secondly, there are no terminators in the data arrays. 其次,数据阵列中没有终结器。 You could use a nominal value such as -1 for example. 例如,您可以使用标称值,例如-1。 Note that the pointer p is derefenced ( *p
) to get the value p points to: 请注意,指针p是derefenced( *p
)以获得值p指向:
int a [] = {1,2,5,7,8,-1}; // in main
int ReturnSize_INT(void *a)
{
a = (int*)a;
int count = 0 ;
int *p = (int*)a;
while(*p != -1)
{
count++;
p++;
}
return count;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.