Consider:
#include <stdio.h>
int f() {
return 20;
}
int main() {
void (*blah)() = f;
printf("%d\n",*((int *)blah())()); // Error is here! I need help!
return 0;
}
I want to cast 'blah' back to (int *) so that I can use it as a function to return 20 in the printf statement, but it doesn't seem to work. How can I fix it?
This might fix it:
printf("%d\n", ((int (*)())blah)() );
Your code appears to be invoking the function pointed to by blah, and then attempting to cast its void return value to int *, which of course can't be done.
You need to cast the function pointer before invoking the function. It is probably clearer to do this in a separate statement, but you can do it within the printf call as you've requested:
printf("%d\n", ((int (*)())blah)() );
Instead of initializing a void pointer and recasting later on, initialize it as an int pointer right away (since you already know it's an int function):
int (*blah)() = &f; // I believe the ampersand is optional here
To use it in your code, you simply call it like so:
printf("%d\n", (*blah)());
typedef the int version:
typedef int (*foo)();
void (*blah)() = f;
foo qqq = (foo)(f);
printf("%d\n", qqq());
Related
I have a struct that contains a declaration like this one:
void (*functions[256])(void) //Array of 256 functions without arguments and return value
And in another function I want to define it, but there are 256 functions!
I could do something like this:
struct.functions[0] = function0;
struct.functions[1] = function1;
struct.functions[2] = function2;
And so on, but this is too tiring, my question is there some way to do something like this?
struct.functions = { function0, function1, function2, function3, ..., };
EDIT: Syntax error corrected as said by Chris Lutz.
I have a struct that contains a declaration like this one:
No you don't. That's a syntax error. You're looking for:
void (*functions[256])();
Which is an array of function pointers. Note, however, that void func() isn't a "function that takes no arguments and returns nothing." It is a function that takes unspecified numbers or types of arguments and returns nothing. If you want "no arguments" you need this:
void (*functions[256])(void);
In C++, void func() does mean "takes no arguments," which causes some confusion (especially since the functionality C specifies for void func() is of dubious value.)
Either way, you should typedef your function pointer. It'll make the code infinitely easier to understand, and you'll only have one chance (at the typedef) to get the syntax wrong:
typedef void (*func_type)(void);
// ...
func_type functions[256];
Anyway, you can't assign to an array, but you can initialize an array and copy the data:
static func_type functions[256] = { /* initializer */ };
memcpy(mystruct.functions, functions, sizeof(functions));
I had the same problem, this is my small program to test the solution. It looks pretty straightforward so I thought I'd share it for future visitors.
#include <stdio.h>
int add(int a, int b) {
return a+b;
}
int minus(int a, int b) {
return a-b;
}
int multiply(int a, int b) {
return a*b;
}
typedef int (*f)(int, int); //declare typdef
f func[3] = {&add, &minus, &multiply}; //make array func of type f,
//the pointer to a function
int main() {
int i;
for (i = 0; i < 3; ++i) printf("%d\n", func[i](5, 4));
return 0;
}
You can do it dynamically... Here is a small example of a dynamic function array allocated with malloc...
#include <stdio.h>
#include <stdlib.h>
typedef void (*FOO_FUNC)(int x);
void a(int x)
{
printf("Function a: %d\n", x);
}
void b(int x)
{
printf("Function b: %d\n", x);
}
int main(int argc, char **argv)
{
FOO_FUNC *pFoo = (FOO_FUNC *)malloc(sizeof(FOO_FUNC) * 2);
pFoo[0] = &a;
pFoo[1] = &b;
pFoo[0](10);
pFoo[1](20);
return 0;
}
From the top of my head and untested.
// create array of pointers to functions
void (*functions[256])(void) = {&function0, &function1, &function2, ..., };
// copy pointers to struct
int i;
for (i = 0; i < 256; i++) struct.functions[i] = functions[i];
EDIT: Corrected syntax error as said by Chris Lutz.
You could do that while declaring your struct instance:
function_structur fs = { struct_field1,
struct_field2,
{function0, function1, ..., function255},
struct_field3,
... };
You cannot use this shortcut for initialize arrays after the array has been declared: if you need to do that, you'll have to do it dynamically (using a loop, a memcpy or something else).
If you want to post-initialize an array using form like {func1, func2, ...}, this can be accomplished in the following way (using GCC):
UPD (thanks to Chris Lutz for remarks)
Define a macro like this:
#define FUNCTION_VECTOR_COPY(destVec, sourceVec) memcpy(destVec, sourceVec, sizeof(sourceVec))
And pass source vector using Compound Literals, as follow:
#include <string.h>
...
void (*functions[256])();
...
FUNCTION_VECTOR_COPY (functions, ((void(*[])()) {func1, func2, func3}));
I'm trying to find out the proper way to return an integer from a void * function call within C.
ie ..
#include <stdio.h>
void *myfunction() {
int x = 5;
return x;
}
int main() {
printf("%d\n", myfunction());
return 0;
}
But I keep getting:
warning: return makes pointer from integer without a cast
Is there a cast I need to do to make this work? It seems to return x without problem, the real myfunction returns pointers to structs and character strings as well which all work as expected.
It's not obvious what you're trying to accomplish here, but I'll assume you're trying to do some pointer arithmetic with x, and would like x to be an integer for this arithmetic but a void pointer on return. Without getting into why this does or doesn't make sense, you can eliminate the warning by explicitly casting x to a void pointer.
void *myfunction() {
int x = 5;
return (void *)x;
}
This will most likely raise another warning, depending on how your system implements pointers. You may need to use a long instead of an int.
void *myfunction() {
long x = 5;
return (void *)x;
}
A void * is a pointer to anything, you need to return an address.
void * myfunction() {
int * x = malloc(sizeof(int));
*x=5;
return x;
}
That being said you shouldn't need to return a void * for an int, you should return int * or even better just int
Although you'd think the easiest way to do this would be:
void *myfunction() {
int x = 5;
return &x; // wrong
}
this is actually undefined behaviour, since x is allocated on the stack, and the stack frame is "rolled up" when the function returns. The silly but correct way is:
void *myfunction() {
int *x = malloc(sizeof(int));
*x = 5;
return x;
}
Please never, ever write code like this, though.
I compiled this source with gcc -pedantic:
#include <stdio.h>
void *myfunction() {
size_t x = 5;
return (void*)x;
}
int main() {
printf("%d\n", *(int*)myfunction());
return 0;
}
There is no warnings
Is it possible to declare some function type func_t which returns that type, func_t?
In other words, is it possible for a function to return itself?
// func_t is declared as some sort of function pointer
func_t foo(void *arg)
{
return &foo;
}
Or would I have to use void * and typecasting?
No, you cannot declare recursive function types in C. Except inside a structure (or an union), it's not possible to declare a recursive type in C.
Now for the void * solution, void * is only guaranteed to hold pointers to objects and not pointers to functions. Being able to convert function pointers and void * is available only as an extension.
A possible solution with structs:
struct func_wrap
{
struct func_wrap (*func)(void);
};
struct func_wrap func_test(void)
{
struct func_wrap self;
self.func = func_test;
return self;
}
Compiling with gcc -Wall gave no warnings, but I'm not sure if this is 100% portable.
You can't cast function pointers to void* (they can be different sizes), but that's not a problem since we can cast to another function pointer type and cast it back to get the original value.
typedef void (*fun2)();
typedef fun2 (*fun1)();
fun2 rec_fun()
{
puts("Called a function");
return (fun2)rec_fun;
}
// later in code...
fun1 fp = (fun1)((fun1)rec_fun())();
fp();
Output:
Called a function
Called a function
Called a function
In other words, is it possible for a function to return itself?
It depends on what you mean by "itself"; if you mean a pointer to itself then the answer is yes! While it is not possible for a function to return its type a function can return a pointer to itself and this pointer can then be converted to the appropriate type before calling.
The details are explained in the question comp.lang.c faq: Function that can return a pointer to a function of the same type.
Check my answer for details.
Assume the function definition
T f(void)
{
return &f;
}
f() returns a value of type T, but the type of the expression &f is "pointer to function returning T". It doesn't matter what T is, the expression &f will always be of a different, incompatible type T (*)(void). Even if T is a pointer-to-function type such as Q (*)(void), the expression &f will wind up being "pointer-to-function-returning-pointer-to-function", or Q (*(*)(void))(void).
If T is an integral type that's large enough to hold a function pointer value and conversion from T (*)(void) to T and back to T (*)(void) is meaningful on your platform, you might be able to get away with something like
T f(void)
{
return (T) &f;
}
but I can think of at least a couple of situations where that won't work at all. And honestly, its utility would be extremely limited compared to using something like a lookup table.
C just wasn't designed to treat functions like any other data item, and pointers to functions aren't interchangeable with pointers to object types.
what about something like this:
typedef void* (*takesDoubleReturnsVoidPtr)(double);
void* functionB(double d)
{
printf("here is a function %f",d);
return NULL;
}
takesDoubleReturnsVoidPtr functionA()
{
return functionB;
}
int main(int argc, const char * argv[])
{
takesDoubleReturnsVoidPtr func = functionA();
func(56.7);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
typedef void *(*fptr)(int *);
void *start (int *);
void *stop (int *);
void *start (int *a) {
printf("%s\n", __func__);
return stop(a);
}
void *stop (int *a) {
printf("%s\n", __func__);
return start(a);
}
int main (void) {
int a = 10;
fptr f = start;
f(&a);
return 0;
}
It is not possible for a function to return itself by value. However it is possible itself to return by a pointer.
C allows to define function types that take undefined number of parameters and those those types are compatible with function types that take defined parameters.
For example:
typedef void fun_t();
void foo(int);
fun_t *fun = foo; // types are fine
Therefore the following function would work.
void fun(void (**ptr)()) {
*ptr = &fun;
}
And below you can find the exemplary usage:
#include <stdio.h>
void fun(void (**ptr)()) {
puts("fun() called");
*ptr = &fun;
}
int main() {
void (*fp)();
fun(&fp); /* call fun directly */
fp(&fp); /* call fun indirectly */
return 0;
}
The code compiles in pedantic mode with no warnings for C89 standard.
It produces the expected output:
fun() called
fun() called
There's a way, you just try this:
typedef void *(*FuncPtr)();
void *f() { return f; }
int main() {
FuncPtr f1 = f();
FuncPtr f2 = f1();
FuncPtr f3 = f2();
return 0;
}
If you were using C++, you could create a State object type (presuming the state machine example usage) wherein you declare an operator() that returns a State object type by reference or pointer. You can then define each state as a derived class of State that returns each appropriate other derived types from its implementation of operator().
The function proto type like int xxxx(int) or void xxx(int)
You could use a global variable (or, a little better, you could use a static variable declared at file scope), or you could change your functions to take an output parameter, but ultimately you should just use a return statement, since that's really what it's for.
The two standard ways to return values out of functions in C are to either do it explicitly with the return statement, or to use a pointer parameter and assign into the object at the pointer.
There are other ways, but I'm not going into them for fear of increasing the amount of evil code in the world. You should use one of those two.
Use pass by reference:
void foo(int* x, int* y) {
int temp;
temp = *x;
x* = *y;
y* = temp;
}
void main(void) {
int x = 2, y=4;
foo(&x, &y);
printf("Swapped Nums: %d , %d",x,y);
}
You could have a global variable that you assign the value to.
You could pass an object that stores the integer, and if you change it in the function, it'll change elsewhere too, since objects are not value type.
It also depends on the programming language that you're using.
EDIT: Sorry I didn't see the C tag, so ignore my last statement
Typically you provide a reference to an external variable to your function.
void foo(int *value)
{
*value = 123;
}
int main(void)
{
int my_return_value = 0;
foo(&my_return_value);
printf("Value returned from foo is %d", my_return_value);
return 0;
}
The simple answer is given a prototype like the first one you must use the return statement as the int return value dictates it.
In principle it is possible to do something horrible like cast a pointer to an int and pass it in as a parameter, cast it back and modify it. As others have alluded to you must be sure you understand all the implications of doing this, and judging by your question I'd say you don't.
int wel();
int main()
{
int x;
x = wel();
printf("%d\n",x);
return 0;
}
int wel()
{
register int tvr asm ("ax");
tvr = 77;
}
Compiled with GCC compiler in ubuntu machine. In borland compiler, different way to return.
If you need to return more than one value, why not use a pointer to a new allocated struct?
typedef struct { int a, char b } mystruct;
mystruct * foo()
{
mystruct * s = (mystruct *) malloc(sizeof(mystruct));
return s;
}
Not tested, but should be valid.
char *test = "hello";
test = change_test("world");
printf("%s",test);
char* change_test(char *n){
printf("change: %s",n);
return n;
}
im trying to pass a 'string' back to a char pointer using a function but get the following error:
assignment makes pointer from integer without a cast
what am i doing wrong?
A function used without forward declaration will be considered having signature int (...). You should either forward-declare it:
char* change_test(char*);
...
char* test = "hello";
// etc.
or just move the definition change_test before where you call it.
printf() prints the text to the console but does not change n. Use this code instead:
char *change_test(char *n) {
char *result = new char[256];
sprintf(result, "change: %s", n);
return result;
}
// Do not forget to call delete[] on the value returned from change_test
Also add the declaration of change_test() before calling it:
char *change_test(char *n);
You're converting an integer to a pointer somewhere. Your code is incomplete, but at a guess I'd say it's that you're not defining change_test() before you use it, so the C compiler guesses at its type (and assumes it returns an integer.) Declare change_test() before calling it, like so:
char *change_test(char *n);
thanks a bunch guys! didnt think i would have this problem solved by lunch. here is the final test class
/* standard libraries */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* change_test(char*);
int main(){
char *test = "hello";
test = change_test("world");
printf("%s",test);
return (EXIT_SUCCESS);
}
char* change_test(char *n){
return n;
}