开发者

Basic C pointer question

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)


It should be:

*sum += j;

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


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

 *sum += j


You have to write *sum + = j;

This suffices


You could also declare a simple struct to hold the two values, then pass in a pointer to an instance of that structure. That way you could manipulate both variables and they'd retain their values after the function returns.

struct loop_sum_struct {
    int loop_ctr;
    int sum;
} loop_sum;

loop_function(&loop_sum);

void loop_function(loop_sum_struct *s) {
    int len = 10;
    for(s->loop_ctr = 0; s->loop_ctr loop_ctr++) {
        s->sum += s->loop_ctr;
    }
}


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);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜