Jump to content

Recommended Posts

I just started with SourceBoost C and I'm pretty happy with it. One of the disappointments was the inability to use arrays of function pointers. I'm not sure of the source for this limitation, but these are smart guys so I assume there's a good reason for it.

 

Anyway, I started playing around and tried saving a function pointer as an int, and lo and behold it worked. Then I made an array of ints and stuffed a bunch of function pointers therein. That seems to work fine too. Or at least it works when stepping through it with the simulator/debugger.

 

I haven't examined the code produced by this very closely, but I wonder if I'm wandering into dangerous territory here. Can anyone see if I'm about to hang myself with this rope?

 

#include <system.h>
#pragma CLOCK_FREQ	20000000


//======================================================
// These are the functions pointed to.
char test1( void ) { return 'a'; }
char test2( void ) { return 'b'; }
char test3( void ) { return 'z'; }


int funcPtrs[3];

//======================================================
void main( void )
{
char (*func)( void );		// Pointer to function.
char c = 0;

funcPtrs[0] = (int)test1;
funcPtrs[1] = (int)test2;
funcPtrs[2] = (int)test3;

for( char i = 0; i < 3; i++ )
{
	func = funcPtrs[i];	// Odd... no casting required?
	c = func();			// C shows the proper value for all 3 iterations.
}

while( 1 );
}

Share this post


Link to post
Share on other sites

While I was persuing the forum I found references to this technique, except to use an char array instead of an int array (because function pointers are actually indices, sort of).

 

So I guess I'm Ok with this.

Share this post


Link to post
Share on other sites
While I was persuing the forum I found references to this technique, except to use an char array instead of an int array (because function pointers are actually indices, sort of).

 

So I guess I'm Ok with this.

 

Yes you can use a char array to hold function pointers. Size of a function pointer is 1 byte and it can be casted to char and back.

 

Regards,

Pavel

Share this post


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...