Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C pointer question

Tags:

c

pointers

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

like image 660
Markus Avatar asked Nov 27 '22 08:11

Markus


2 Answers

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.

like image 107
Tyler McHenry Avatar answered Jan 09 '23 01:01

Tyler McHenry


Write

*sum += j;

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

like image 30
Vladimir Avatar answered Jan 09 '23 02:01

Vladimir