Thiago.K
Thiago.K

Reputation: 1

C++: Problem with pointers in microsoft Visual Studio

I was using as my main IDE codeblocks, but I wanted to try visual studio. When I run the following code in Codeblocks (or an online C++ compiler) I get the right answer (output = 61), but when I put it in visual studio I get a weird answer (output= 90). Can somebody explain what is happening?

#include <iostream>

int sum(int *s, int sz);

int main()
{
    int arr[] = { 1,10,20,30 };
    int siz = sizeof(arr) / sizeof(int);
    int *ptr = arr;
    int output = sum(arr, siz);
    std::cout << "output = " << output << std::endl;
    return 0;
}

int sum(int *int_input, int n)
{
    if (n == 1)
    {
        return *int_input;
    }
    else
    {
        return *int_input + (sum(++int_input, --n));
    }
}


Thank you for the help :)

Upvotes: 0

Views: 267

Answers (1)

Midren
Midren

Reputation: 409

Here you have unspecified behaviour in the next line

*int_input + (sum(++int_input, --n))

You cannot say for sure is dereferencing *int_input is first or incrementing ++int_input. To fix it, you need to rewrite code nextly:

*int_input + (sum(int_input+1, --n))

Upvotes: 1

Related Questions