
Struct containing pointer to function
: My goal is to be able to have a struct containing a pointer to a function,
: (*func_point)(), which I can initialise to some function, func(), and make
: calls to that function via the pointer/structure.
: I am using Borland Turbo C, v3.0 with the source options set to ANSI C and
: the whole sha-bang is running in a DOS window on win95.
: As the function stands (see below), it compiles just fine, but when I run
: it I get the following output:
: Func called, k = 4
: ret_val = 4
: Null pointer assignment
: I understand (via the compiler's online help) that the "Null pointer
: assignment" is due to some value being stored to an uninitialised pointer
: but it isn't obvious to me where this is.
: I would appreciate anyone's help with this.
: Thank you...
: David C
: /** Start program *************************************/
: #include <stdio.h>
: /* Function prototype */
: int func(int k);
: struct test_fptr
: {
: int (*func_point)(int);
: };
: int main(void)
: {
: struct test_fptr *p_stru = NULL;
: int ret_val;
: p_stru->func_point = func;
Here's your problem. Your pointer p_stru points to NULL, yet you try to
access its fields. This causes undefined behaviour.
To correct this:
Put #include <stdlib.h> at the top of the file
Insert here:
p_stru=malloc(sizeof(struct test_fptr));
if (!p_stru)
{
printf("Sorry user, I don't have enough memory available\n");
return 0;
Quote:
}
: ret_val = p_stru->func_point(4);
: printf("ret_val = %d\n", ret_val);
And insert here:
free(p_stru);
: return 0;
: }
: int func(int k)
: {
: printf("Func called, k = %d\n", k);
: return k;
: }
: /** End program ***************************************/
--
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #80 D+ ADA N+++ |
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Ice cream sales somehow cause drownings: both happen in summer."
- Antti Voipio & Arto Wikla