Stanimirovv
Stanimirovv

Reputation: 3172

Getting wrong output

This is the code: A[0] (in the main function) should be equal to 0, not 1. I can't find my mistake. I suppose the problem is somewhere in the and1 function, but again, I can't seem to be able to find it. Anyway I am pretty sure that the first sentence covered the problem pretty well, but the website is forcing me to write more information.

#include <iostream>
#include <string>
// V and ^ or
using namespace std;
int A[] = {0, 1, 1};
int B[] = {1, 0, 1};

 int* and1(int A[], int B[])
{
    int ret[3];
    for(int i = 0; i < 3; i++)
    {
        if(A[i] == 1 && B[i] == 1 )
        {
            ret[i] = 1;
        }
        else
        {
            ret[i] = 0;
        }
    }
    return ret;
}

int* or1(const int A[], const int B[])
{
    int ret[] = {0 ,0 ,0};
    for(int i = 0; i < 3; i++)
    {
        if(A[i] == 1 || B[i] == 1)
        {
            ret[i] = 1;
        }
        else
        {
            ret[i] = 0;
        }
    }
    return ret;
}

int main()
{
    int* a = and1(A, B);
    int* b = or1(A, B);
    if(*(a+1) == *(b+1))
    {
        cout << a[0] << endl;
    }
    return 0;
}

Upvotes: 0

Views: 66

Answers (3)

masoud
masoud

Reputation: 56529

You are returning a pointer of a temporary array from function and1. And the result is undefined.

int* and1(int A[], int B[])
{
   int ret[3];
   //...
   return ret;
}

int* a = and1(A, B); // <-- Undefined behavior

After return ret, the arrayret destroys and it doesn't mean more to use.

Upvotes: 2

uba
uba

Reputation: 2031

int ret[3]; in function and1 is a variable local to and1. When and1 completes execution, it goes out of scope. So returning its address does not make sense. Instead, you could pass the ret array to and1 (similarly for or1), with the prototype being:

void and1(const int A[], const int B[], int ret[]);

Upvotes: 2

Alok Save
Alok Save

Reputation: 206616

You are returning pointers to arrays which are local to the function and these local arrays do not exist when the function scope { } ends. What you get is a pointer pointing to something that does not exist and an Undefined behavior.

Upvotes: 3

Related Questions