tags:

views:

251

answers:

7

Hi all,

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

+9  A: 

Write

*sum += j;

What you are doing is incrementing the pointer (Probably not what you wanted)

Vladimir
Also "j" must be declared.
Judas Imam
+3  A: 

It should be:

*sum += j;

so you increment the value pointed to instead of the local pointer variable.

Nikolai N Fetissov
+17  A: 

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.

Tyler McHenry
@Tyler : +1 , yeah j must be defined.
Chankey Pathak
+2  A: 

You don't need to create extra variable but in the loop you need to do

 *sum += j

taskinoor
A: 

How about this ?

As you are already returning int. So, another way is to just change the signature to

int loop_function(int sum)

and at the time of calling

int sum = 0;

...

sum = loop_function(sum);

DeltaRogue
The OP is trying to return two things from one function: the loop counter, and the sum. In C, this typically means passing in a pointer and modifying what it points to.
David Thornley
Ah, true !I just looked at the definition only in the OP which is not storing the return value anywhere but I see your point now. Thanks !
DeltaRogue
A: 

You have to write *sum + = j;

This suffices

ravi
A: 
TMN