This question already has answers here:
what does it mean to convert int to void* or vice versa?
(6 answers)
Closed 9 years ago.
#include <stdio.h>
void pass(void* );
int main()
{
int x;
x = 10;
pass((void*)x);
return 0;
}
void pass(void* x)
{
int y = (int)x;
printf("%d\n", y);
}
output: 10
my questions from the above code..
what happens when we typecast normal variable to void* or any pointer variable?
We have to pass address of the variable to the function because in function definition argument is pointer variable. But this code pass the normal variable ..
This format is followed in linux pthread programming... I am an entry level C programmer. I am compiling this program in linux gcc compiler..
I'm only guessing here, but I think what you are supposed to do is actually pass the address of the variable to the function. You use the address-of operator & to do that
int x = 10;
void *pointer = &x;
And in the function you get the value of the pointer by using the dereference operator *:
int y = *((int *) pointer);
Please read why glib provide macros for this kind of conversions, there's no need to repeat the text here. The main point is: a pointer has a platform dependent size.
If you are planning to use pthreads and you are planning to pass the pass function to pthread_create, you have to malloc/free the arguments you are planning to use (even if the threaded function just need a single int).
Using an integer address (like &x) is probably wrong, indeed each modification you will execute on x will affect the pass behaviour.
Related
This question already has answers here:
Passing by reference in C
(19 answers)
Closed 4 years ago.
I don't really see any difference, with passing pointers to functions and calling a function by reference. Am I right
#include <stdio.h>
int multi;
int multiplication(int *a, int *b){
multi = (*a) * (*b);
return multi;
}
int main()
{
int X = 2, Y=3;
multiplication(&X, &Y);
printf("%d", multi);
return 0;
}
From the example code you show, you obviously mean pass by reference, not call by reference.
There is no pass by reference in C, it's always pass by value. Of course, you can get the effect of pass by reference by passing a pointer to something. The pointer is your reference. It's again passed by value, but you use that value to access some other object.
Languages that have pass by reference will typically use pointers to implement it.
This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed 8 years ago.
What is the difference between passing by reference the parameters in a function and passing pointer variables as a parameter in a function ?
There is no pass by reference in C, it's always pass by value.
C developers can emulate pass by reference, by passing the pointers to a variable and the accessing it using dereferencing within the function. Something like the following, which sets a variable to 42:
static void changeTo42 (int *pXyzzy) {
*pXyzzy = 42;
}
:
int x = 0;
changeTo42 (&x);
Contrast that with the C++ true pass by reference, where you don't have to muck about with pointers (and especially pointers to pointers, where even seasoned coders may still occasionally curse and gnash their teeth):
static void changeTo42 (int &xyzzy) {
xyzzy = 42;
}
:
int x = 0;
changeTo42 (x);
I would implore ISO to consider adding true references to the next C standard. Not necessarily the full capability found in C++, just something that would fix all the problems people have when calling functions.
You might be thinking of C++. I'll cover that below.
In C there is no passing by reference. To accomplish the same feat, you can send a pointer to a variable as an argument and dereference the pointer in the method, as shown in paxdiablo's comment.
In C++, you could accomplish the same thing if you tried to pass by reference C-style (as explained previously) or if you tried passing the arguments as such:
static void multiply(int& x){
x * 7;
}
void main(){
int x = 4;
multiply(x);
}
The variable x at the end of this program would equal 28.
This question already has answers here:
Assigning Float Pointers in C [closed]
(3 answers)
Closed 9 years ago.
I'm new to C, and I'm writing a very basic function that takes an integer pointer as a parameter. Inside the function, a float pointer must be created. This function must assign the value of the integer pointer to the float and then return the float. Here's my code at the moment:
float * function(const int *x)
{
float *p = (float*)x;
return p;
}
But this results in an error that reads as such when run: "free(): invalid pointer: 0x00007fffc0e6b734". Suffice it to say, I'm very confused. Any insights you can offer would be much appreciated!
Being new to C, are you familiar with the scope of variables? (Part of) the short version of variable scope is that if you don't do a little something extra, a variable created in a function only exists inside that function. Why that's important to you: if you return a pointer to a variable that you created inside a function (without doing that little something extra) that pointer will point to an area of memory that may or may not contain the value that you assigned to it. One way to do what you want is this:
float *makefloat(int *x) {
// static keyword tells C to keep this variable after function exits
static float f;
// the next statement working from right to left does the following
// get value of pointer to int (x) by dereferencing: *x
// change that int value to a float with a cast: (float)
// assign that value to the static float we created: f =
f = (float) *x;
// make pointer to float from static variable: &f
return &f;
}
In general I seem to see more functions that accept a pointer to the variable that is to be modified, then in that function the new value is created and assigned to the area in memory referenced by the pointer. Because that area of memory exists outside of the scope of the function, there is no need to worry as much about scope and static variables. Another cool thing about static variables is that the next time the function is called, the static variable has the same value it did when the function last exited. Explained on Wikipedia.
Good explanation of * and &: Pointers in C: when to use the ampersand and the asterisk
Your function only performs a pointer conversion. A function call of the form
q = function(p); /* p is a "const int *" pointer,
q is assignment comaptible with "float *". */
can be replaced by the expression:
q = (float *) p;
by itself, this doesn't do any harm. The problem is elsewhere in your program.
Note that most type punning, like accessing an object of type int using an expression of type float via pointers, is undefined behavior in the C language. This isn't going on in the example code, but things are headed in that direction; the pointer is probably being prepared for carrying out type punning.
Consider that int and float don't necessarily even have the same size; and that is not the only consideration. In code like this:
int i = 42;
/* now treat i as a float and modify it sneakily */
*((float *) &i) = 3.14;
printf("i = %d\n", i);
the output of the printf can still be 42. The optimizing compiler can put i into a machine register, whereas the sneaky assignment might be performed on the memory location that serves as the "backing storage" for i, and so i appears unchanged since the printf call uses the register-cached copies. The compiler is not required to consider that a modification of an object designated by the type float might affect the value of an object of type i (even if they otherwise have the same size, so there is no collateral damage done by the assignment, like overwriting other objects).
In the real world, sometimes it is necessary to write a code that manipulates floating-point objects as if they were integers: typically unsigned int integers, to gain access to the bitwise representation of the float. When this is done, you have to use unions, or perhaps compiler-specific features, like GCC's -fno-strict-aliasing option which causes the compiler to optimize more cautiously in the face of type punning. in that kind of code, you make sure that the assumptions are all warranted about the sizes of types and such, with #ifdef-s for different platforms, perhaps based on values pulled from running configured scripts to detect platform features.
Needless to say, this is not a good way to be learning C at a beginner level.
This question already has answers here:
How do I quiet the C compiler about a function pointer takes any number of arguments?
(5 answers)
Closed 9 years ago.
I'd like to ask if it's possible to make function pointer that can be assigned to any function later i have.
typedef struct
{
char *name ;
void (*func0)(void) ;
}option;
int test(int i)
{
return i;
}
How to cast either the option parameter or the function so later I'd be able to call the option parameter and use it as a function?
I tried:
op.func0= test ;
or:
(int)op.func0= test ;
failed.
In C you can store your function as
void * (*func)();
func = test;
But when you invoke it you have to cast it to the appropriate type
int ret = ((int (*)())func)(a);
This is not considered safe on arbitrary target architectures. On x86 it should work, but you should avoid those tricks on other architectures.
Edit:
If you wish to avoid the typecast warning then make the assignment as
func = (void * (*)())test;
With this typecast it compiles with gcc -pedantic
It is okay to cast your function to a different function pointer type, you just have to make sure to cast it back before using it. Here is an example:
#include <stdio.h>
typedef struct
{
char *name ;
void (*func0)(void) ;
} option;
int test(int i)
{
return i;
}
int main(int argc,char **argv)
{
option a;
int i;
a.func0 = (void(*)(void))test;
i = ((int(*)(int))a.func0)(5);
printf("%d\n",i);
return 0;
}
It outputs 5.
If you have a limited (i.e., practical) limit on the call signatures you may likely be a able to use union of pointers of different signatures:
typedef union call_sigs_union
{
void *void_void; // pure void pointer
int (*int_sig_void)(void); // returns integer with no arguments
int (*int_sig_int)(int); // returns integer with single int arg
. . .
} sigs_t;
The advantage of this is you better warnings out of the compiler if you are doing something wrong than if you cast everything.
Caveat: this is not guaranteed across many architectures as, in theory, different return types, and perhaps signatures, can have different pointer types. While I have read about a few systems this actually happens on I have not heard about the major players in popular use having such behavior. Intel X86, Itanimum, Sun SPARC, and IBM RISC are some of the well-behaved systems I have used. Noting I have read on the ARM architecture leads me to believe these would be trouble.
The odd behavior is usually limited to special-purpose processors. Can anyone refresh my memory on systems that this would break on?
This question already has answers here:
How do function pointers in C work?
(12 answers)
Closed 9 years ago.
In a book, I came across the following question.
The problem which I am facing is, what is a function pointer? How does it work and what is the syntax for it's declaration.
Point the error in given code.
main()
{
int (*p)()=fun;
(*p)();
}
fun()
{
printf("Hi..");
}
my first question is, What does following code snipet signifies?
int (*p)()=fun;
(*p)();
and second obvious question what is the error in the given code..??
refer to ionela.voinescu's answer for solution.. it is same as that written in solution manual..thnx
int (*p)() = fun declares a pointer to a function that returns int, then assigns the address of the function fun to that pointer. (*p)() calls whatever function p is pointing to.
Problems with your code:
fun and main should have a return type. Your compiler might not demand it and assume they return ints, but you should give them one nonetheless.
You need to declare fun above main, or use a prototype
Also, (*p)() is unnecessary; you can just use p().
As a side note, because function pointer syntax is relatively ugly, it's fairly common to see typedefs such as
typedef int(*IntFunc)();
which would allow you to declare and use p like so:
IntFunc p = fun;
p();
The correct code is the following:
#include <stdio.h>
int fun();
int main(){
int (*p)()=fun;
(*p)();
return 0;
}
int fun(){
printf("Hi..");
return 0;
}
1.
int fun();
You have to declare your function before using it in main; Otherwise main wont recognize it.
2.
int (*p)() : Declaration of a variable p which is a pointer to a function that returns int and has no arguments(or undefined number of arguments, depending on the standard).
3.
int fun();
.........
int (*p)()=fun;
In order for this to work fun must also return int. Meaning when assigning a value to a variable this must have a type which corresponds with the declaration of the variable. When assigning a value to a pointer to a function that returns int and has no arguments the function assigned to it must also return int and have no arguments (or undefined number of arguments, depending on the standard).
4.
(*p)();
You call the function p which now points to fun.
fun is name of the the function itself.
int (*p)()
is the definition of the function pointer like 'int a' is the definition of an integer.
int * is the pointer itself, () means it is a pointer to a function.
(*p)();
This is the execution of the function of the function pointer p, i.e. p is assigned to the function fun, which is executed by calling the content of the pointer p, thus (*p)();