-3

What does the following function do? Its output is foobar(k) = 7, k = 7.

int foobar(int* n){
   *n = *n +1;
   return *n;
}

int k = 6;
printf("foobar(k) = %d,",foobar(&k) );
printf(" k = %d\n", k);
Dada
  • 6,313
  • 7
  • 24
  • 43
  • That function only does two things: sets the value of an `int` target addressed by a pointer using pointer-dereference to both read and write to the provided target address, and return the same value just-set. Which of those two things don't you understand? – WhozCraig Jul 04 '21 at 20:38
  • Thanks very much for the very quick answer. for example, input is int 6, then *6 should be the base address for it? then what happens to *n = *n + 1? So 1 was added to the address? Sorry I am very new to this. Please give a example. Thanks again. –  Jul 04 '21 at 20:43
  • In your case, input isn't 6, but instead the address of `k`. Dereferencing `n` effectively allows you to modify `k` then. So in the function, it dereferences `n` and increments that, basically incrementing `k` in the process. – mediocrevegetable1 Jul 04 '21 at 20:46
  • 4
    Your problem seems to be basic understanding of C fundamentals. I strongly suggest a [book on C](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). `*n + 1` doesn't evaluate to "add one to an address" , it evaluates to "add one to the int value stored at an address" (in this case the address held in the pointer `n`, and said-value is both fetched, and eventually stored, using the dereference operator `*` on that pointer). Anyway, you need to review pointer fundamentals. They're easily the hardest thing to grasp in C, and you won't just "get it" casually. – WhozCraig Jul 04 '21 at 20:48
  • But why the printed foobar(&k) is still 7? What does incrementing k mean? Thanks very much! –  Jul 04 '21 at 20:50
  • thanks guys for your patience. I understand now! –  Jul 04 '21 at 21:08

1 Answers1

1

The function foobar simply take an integer pointer as input parameter. On the code increase the content of that pointer by 1 and then returns the content of pointer. When you call fooar by this way: foobar(&k) in fact you passing foobar pointer of k variable (that's what foobar expected) when using *n in code you mean that you working with content of pointer (not pointer itself)

Mohammad
  • 96
  • 5