+ 2
C Module 4 Quiz, Question #4
I am so confused about question number 4. I initially felt like I understood pointers and the * and & operators, but I cannot seem to find anything on how to call this particular function pointer. Honestly, the whole idea of a function pointer seems completely convoluted to me; I just don't get it. If anybody has some insight as to the significance, syntax, or just the answer itself that would be really helpful. Thanks!
9 Antworten
+ 4
Perfect Answer :
#First blank is
Void
#Second blank is
&
#Third blank is
*
+ 2
Fill in the blanks to triple the value of the num variable via the void pointer.
The correct ans :
float num = 3.14;
void
*ptr =
&
num;
*
((float*)ptr) *= 3;
0
Not a function pointer :) As Thirt13n pointed out we are just converting a float to a void* and back.
Truthfully C doesn't do a very good job of selling function pointers, the syntax is absolutely terrible.
Significance? In C probably not so much, but I see you did javascript aswell. This stuff is really common in js:
var f = function () { console.log("Hi!"); };
button.addEventListener("click", f);
In other words we can put functions in variables. Super useful, js devs do it *everywhere*.
Now in js everything is a `var` and it just sort of works somehow, but in C all variables need to have a type; and if you have a function in a variable, the variable's type needs to reflect the function's type somehow.
Thus we end up with gnarly stuff like `void (*foo)(int, int)`. Other languages have prettier syntax for function types but C is old what are you gonna do.
To translate the js example into nonsense C:
void f() { printf("Hi!"); }
void onEvent (char* what, void (*fp)()){ ... }
onEvent("click", &f);
0
float num=3.14;
void *ptr=#
*((float*)ptr)*=3;
0
ans =1
0
create a pointer to the variable called demo then output its value using the pointer
0
What is The largest of the arrays.if arrays form 35 12 3 8
0
Fill in the blanks to declare a string, then output its 5th character.
x[] = "Hello there
;
printf("
", x[
]);
- 3
Q.triple the value of " num " using void pointer
float num=3.14;
.......ptr=....num;
....((float*)ptr)*=3;
>>>as in question pointer " ptr " is void first blank's answer is " void " and then addressof " & "
>>>here num is casted to float , because when we dereference void pointer we must first type cast the pointer before dereferencing with " * " . ptr points to address of " num " if we dereference " ptr " then only we can make multiply to num , so third blank is for dereference " * " ;
here third " * " for multiplication !
HOPE THIS HELP !
(please correct me if I'm wrong)