0

I have two functions, I need one to add a value to a variable and the other to print it, but the output is incorrect to what I expect.

What I do is define a function, passing a sum pointer as a parameter, in another function I create the variable that I will pass as a parameter and I invoke the new function passing that variable as an address, but when printing it it fails.

    #include <stdio.h>

    void test() {
        int sum;
        test2(&sum);
        printf("%d",sum);
    }

    void test2(int *sumador) {
        int i;
        for(i = 0; i < 10; i++) {
            sumador += i;
        }
    }

    int main() {
        test();
    }
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Kalifeh
  • 33
  • 4

1 Answers1

3

The problem is that you should dereference the pointer before summing with "i", like this:

*sumador += i;

This happens because "sumador" is a pointer and the content of the pointer is a memory address. In your original code you are adding "i" to the address stored in "sumador", what you actually want is to sum "i" with the content contained in the memory address stored in the pointer, which is the process we called dereferencing.

Another problem is that in function test make sure to initialize the value of the variable sum.

int sum = 0;

Also, because test2 is called inside test, you should declare the function test2 above the function test, not below it, like this:

#include <stdio.h>

void test2(int *sumador) {
    int i;
    for(i = 0; i < 10; i++) {
        *sumador += i;
    }
}

void test() {
    int sum = 0;
    test2(&sum);
    printf("%d",sum);
}


int main() {
    test();
}

I hope I was able to help you, have a nice day!

  • Well, yes actually, I forgot about that, let me make a correction in my post, – MysteRys337 Nov 11 '22 at 21:43
  • @MysteRys337: If you want the person to which you are replying to be automatically notified of your comment, you must write the person's name using the `@` syntax, as I am doing with you. Press the "Help" button when writing a comment for further information. – Andreas Wenzel Nov 11 '22 at 21:48
  • Oh ok, thanks @AndreasWenzel, now I know that hahaha – MysteRys337 Nov 11 '22 at 21:49
  • When writing a comment to a post, the owner of the post will automatically be notified of your comment. But other people will not be notified, unless they happen to be following the question. That is why it is important to use the `@` syntax with the person's name when replying to a comment. I do not have to write your name so that you are notified, because you are the owner of the post to which I am attaching this comment. – Andreas Wenzel Nov 11 '22 at 21:55