(solved)Please help me with C functions return types | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

(solved)Please help me with C functions return types

How does this code produce the output without dereferencing the pointer? I thought I have to dereference the pointer to get the value. https://code.sololearn.com/cUh098lrut3Z/?ref=app

31st May 2021, 4:09 PM
Rishi
Rishi - avatar
4 Answers
+ 1
You are actually assigning the value 16 to the pointer. So instead of holding the address of anything useful in memory this pointer holds the value 16. Dereferencing it will probably result in an error because it doesn't describe a valid memory location you have access to. Normally pointers store memory addresses of some meaningful content in memory, which you can get for example by using the address of operator &. But they can also hold any other value you want them to.
31st May 2021, 5:02 PM
Hape
Hape - avatar
+ 1
Rishi bro as your function expects int* i.e. (integer pointer means pointer having address of an int ) as return type.But what are you doing here is You are returning a int (not int*) due to this it will generate an error like this.... <stdin>:5:12: error: cannot initialize return object of type 'int *' with an lvalue of type 'int' return x; ^ And also you are getting a warning due to print statement, in your print statement your format specifier is for int (%d) but but your argument is of type a int pointer (int*) ,although it will print a garbage value but that's not you expect from your code.. Now after reading the above you can think that to remove error you should return &x (not only x) but later you found that you are getting another error which says you can't return the address of any local variable ,the reason is after execution of function all local variables inside the function become out of scope so they are meaningless and you can't access them outside of your func(continued...
1st Jun 2021, 1:30 AM
saurabh
saurabh - avatar
+ 1
In continuation...... So Now think what can be do to resolve this...so many ways.. I'll suggest you a way is that 1. Expect a pointer type parameter for function and then simply return pointer as per your function also expect this return type e.g. int* star(int* x){ return x; } 2. Now go to your driver code in main() While initialization of pointer `tel` call your function by giving address of x bcz function also expect this type of argument e.g. int *tel = star(&x); 3. In your print , You wanna print value 16 so pass the argument of type int i.e. dereference `tel`(*tel) e.g. print ("%d",*tel); Hope you got it.....
1st Jun 2021, 1:43 AM
saurabh
saurabh - avatar
0
Thank you Hape and $|<|>_@& .I finally installs l understood the concept🙂👏
1st Jun 2021, 2:31 AM
Rishi
Rishi - avatar