簡體   English   中英

輸出錯誤

[英]Getting wrong output

這是代碼:A [0](在主函數中)應等於0,而不是1。我找不到我的錯誤。 我想問題出在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;
}

您將返回指向函數本地數組的指針,並且當函數作用域{ }結束時,這些本地數組不存在。 您得到的是一個指向不存在和未定義行為的指針。

int ret[3]; 在函數and1and1局部變量。 and1完成執行時,它將超出范圍。 因此,返回其地址沒有任何意義。 相反,你可以通過ret陣列and1 (同樣為OR 1),與原型之中:

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

您正在從函數and1返回一個臨時數組的指針。 結果是不確定的。

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

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

return ret ,數組ret銷毀,這並不意味着可以使用更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM