It has been a while since I last programmed C, seems I have forgotten everything in the meantime... I have a very simple pointer question. Assuming that I have a function that computes a sum through loop iteration. Not only should this function return the loop counter but also the sum it computed. Since I can just return one value I assume the best I could do for the sum is declaring a pointer. Can I do that like this:
int loop_function(int* sum)
{
int len = 10;
for(j = 0; j < len; j++)
{
sum += j;
}
return(j);
}
....
int sum = 0;
loop_function(&sum);
printf("Sum is: %d", sum);
Or do I need to define an extra variable that points to sum which I pass then to the function?
Many thanks, Marcus
What you have is correct except for this line:
sum += j;
Since sum
is a pointer, this increments the address contained in the pointer by j
, which isn't what you want. You want to increment the value pointed to by the pointer by j
, which is done by applying the dereference operator *
to the pointer first, like this:
*sum += j;
Also, you need to define j
somewhere in there, but I imagine you know that and it's just an oversight.
Write
*sum += j;
What you are doing is incrementing the pointer (Probably not what you wanted)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With