0

コードは次のとおりです。A[0] (メイン関数内) は 1 ではなく 0 にする必要があります。間違いが見つかりません。問題は and1 関数のどこかにあると思いますが、やはり見つけられないようです。とにかく、最初の文で問題がうまくカバーされていると確信していますが、ウェブサイトは私にさらに情報を書くことを強いています.

#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;
}
4

3 に答える 3

3

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.

于 2013-03-09T07:47:10.310 に答える
2

function から一時配列のポインターを返していますand1。そして、結果は未定義です。

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

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

の後return ret、配列retは破壊され、それ以上使用する意味はありません。

于 2013-03-09T07:50:54.990 に答える
2

int ret[3];in functionand1は にローカルな変数ですand1and1実行が完了すると、範囲外になります。したがって、そのアドレスを返すことは意味がありません。代わりに、 (or1 の場合と同様に) にret配列を渡すことができます。プロトタイプは次のとおりです。and1

void and1(const int A[], const int B[], int ret[]);
于 2013-03-09T07:48:46.853 に答える