Kalifeh
Kalifeh

Reputation: 33

pointers in functions don't return what I want

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

Upvotes: 0

Views: 148

Answers (1)

MysteRys337
MysteRys337

Reputation: 55

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!

Upvotes: 3

Related Questions