C pointer

It has been a while since I last programmed C, it seems I forgot everything at the same time ... I have a very simple question with a pointer. Assuming I have a function that calculates the sum through an iteration of a loop. This function should not only return the cycle counter, but also the amount that he calculated. Since I can simply return a single value, I assume I could have the sum declare a pointer. Can I do it 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 additional variable that indicates the amount that I then pass to the function?

Thanks a lot Marcus

+4
source share
7 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 is not what you want. You want to increase the value indicated by a pointer to j , which is done by applying the markup operator * to the first pointer, for example:

 *sum += j; 

Also, you need to define j somewhere out there, but I think you know this and this is just an oversight.

+17
source

Write

 *sum += j; 

What you do increases the pointer (maybe not what you need)

+9
source

It should be:

 *sum += j; 

so that you increment the value specified instead of the local pointer variable.

+3
source

You do not need to create an additional variable, but in a loop you need to do

  * sum + = j 
+2
source

You need to write * sum + = j;

Enough

+1
source

You can also declare a simple structure to hold two values, and then pass a pointer to an instance of that structure. This way you can manipulate both variables, and they 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;
     }
 }
0
source

How about this?

As you already return int. So, another way is to simply change the signature to

int loop_function (int sum)

and during a call

int sum = 0;

...

sum = loop_function (sum);

-1
source

Source: https://habr.com/ru/post/1316415/


All Articles