+ 2

Confusion in quiz question that may well be confusing other users.

I recently came accross a quiz that asked the output of void f(int * x) { x -= 5; } int main() { int k = 7; f(&k); printf("%d",k); } and says that the answer is 2(it'd be if instead of x-=5 we have *x-=5), when the answer is 7. the thing here is that even though x is a pointer, in C, every argument of a function is passed BY VALUE so if we directly assign some value to an argument, like in x-= 5 it will not change it outside the functions scope, you need to access the memory address of the pointer argument to be able to make changes to it. This needs to be like this even if you want to change the address of a pointer, then you need to take a pointer to a pointer as argument, and change the address of a pointer via dereference(i.e. * operator), like so void addOneToAddr(int ** addr) { *addr += 1; // *addr is pointer to int } and use it like int buf[] = {1,2,3,4}; int * bufptr = buf; // now bufptr points to address of buf[0] addOneToAddr(&bufptr); // now bufptr points to address of buf[1]

25th Oct 2018, 11:56 AM
Bebida Roja
Bebida Roja - avatar
6 Antworten
+ 4
If this code is exactly the same code. Yes the answer should be 7 and not 2. Maybe we should wait a mod to respond the mod will instruct what to do rightly. Edit : Here find one post that can help https://www.sololearn.com/Discuss/645277/is-there-a-way-to-report-a-question-that-i-solved-in-a-challenge-but-feel-that-it-was-incorrect
25th Oct 2018, 12:31 PM
Anya
Anya - avatar
+ 2
Hey, I got that answer right, don't destroy this for me! :'D
25th Oct 2018, 1:09 PM
HonFu
HonFu - avatar
+ 2
Jerry Wang, do you already know about pointers? Because this is not about a missing return statement!
27th Oct 2018, 7:29 AM
HonFu
HonFu - avatar
0
Anya I actually wanted to include that i've reported the question in the question, but I reached the char limit :S
25th Oct 2018, 12:55 PM
Bebida Roja
Bebida Roja - avatar
0
sorry, i didn't see that. but it should be seven anyway
29th Oct 2018, 10:26 AM
Jerry Wang
Jerry Wang - avatar
0
because when pointer x finish the algorithim, the value stored in pointer x is not change, so k stays the same
1st Nov 2018, 2:03 PM
Jerry Wang
Jerry Wang - avatar