Hi all, first time poster here.
I am not sure how "usefull" my question will end up being, but i've been wondering about the following:
You can cast between datatypes, so i was wondering if it was possible to cast a function (using a function pointer) into an array. I am not really thinking about the use of this, just something that came to my mind. For example maybe cast it (the function pointer) into a char array and then itterate through each "block" (byte), displaying the binary representation of it.
To this end i've written the following quick test:
Code:
#include <iostream>
using namespace std;
void foo(void) // test function
{
cout<<"In foo()"<<endl;
}
void printBinary(const char bin) // print binary representation
{
unsigned char dummy=1;
for(int i=7; i>=0; --i)
{
if(bin & (dummy<<i))
cout<<"1";
else
cout<<"0";
}
}
int main()
{
void (*fptr)(void);
fptr=foo;
char* a=(char*)fptr; // cast function pointer into array
cout<<"Size: "<<sizeof(a)<<endl; // will give me the size of the pointer and not the actual size of the function, how would you get the size of the function?
for(int i=0; i<sizeof(a); ++i) // will only print 4 times because sizeof(a) will yield only size of the pointer and not the function
printBinary(a[i]); // print binary representation of each block
cout<<endl;
return 0;
}
Now does this make sense? If not what are some of the mistakes i've made (both syntactically and understanding wise)? Also would it be possible to convert an array back into a function pointer (cast back the other way)?
This is more or less a train of thought that is not really something related to an assignment or required material for my courses, just something that might help my general understand of the language.
Oww yeah, i've just started programming in general for the first time about a year ago.
Any clarification will be greatly appreciated!