簡體   English   中英

意外的 output 數組 function 按地址調用

[英]Unexpected output with array function call by adress

我們目前在 C/C++ 中學習與 arrays 結合的指針,並且必須實現一些 function,為此我們有一個給定的 function 調用。 目標是通過使用數組地址調用 function 來打印出數組值。 output 不是預期的。

我嘗試使用&*打印數組值,也沒有使用這些值。

void ausgabe1D_A(double (*ptr1D)[4]){
    int i{0};
    for (i = 0; i < 4; i++)
        std::cout << *ptr1D[i] << "  ";
}

int main()
{
    double ary1D[4] = {1.1, 2.2, 3.3, 4.4};

    ausgabe1D_A(&ary1D);
}

我預計 output 是:
1.1 2.2 3.3 4.4

相反,我得到了:
0x61fdf0 0x61fe10 0x61fe30 0x61fe50(有和沒有&)
1.1 9.09539e-318 0 0 (帶 *)

編輯:抱歉,如果不清楚,但我們必須用&ary1D 我們正在嘗試不同的方式,您的方式正在以下功能的練習中出現,但現在我們需要它與& -Operator。

當您通過名稱引用數組時,您是通過其指針引用它,因此您的 function 參數是錯誤的。 它應該像

void ausgabe1D_A(double *ptr1D, size_t size){
    int i{0};
    for (i = 0; i < size; i++)
        std::cout << ptr1D[i] << "  ";
}

int main()
{
    double ary1D[4] = {1.1, 2.2, 3.3, 4.4};

    ausgabe1D_A(ary1D,4);
}

這是一個short integer陣列的 memory 的圖片

在此處輸入圖像描述

盡管其他人提供了可能的解決方案,但我將嘗試解釋您的代碼失敗的原因。 表達式double(*ptr1D)[4]指的是指向四個元素(雙精度)數組的指針。 要獲取值,您應該首先取消引用指針,然后才打印出它的第 n 個值,如下所示:

void ausgabe1D_A(double (*ptr1D)[4])
{
  for (int i = 0; i < 4; i++) {
    std::cout << (*ptr1D)[i] << " "; // <-- note the parenthesis
  }
}

您可以利用 arrays 可以衰減為指針的事實,因此您可以編寫類似

#include <iostream>

void ausgabe1D_A(double* ptr1D){
    for (std::size_t i = 0; i < 4; i++)
        std::cout << ptr1D[i] << "  ";
}

int main()
{
    double ary1D[4] = {1.1, 2.2, 3.3, 4.4};
    ausgabe1D_A(ary1D);
}

它的工作方式是指針ptr1d本質上是數組第一個元素的地址。

其他答案已經指出了數組不能作為參數傳遞並衰減為指針的特殊性。

但是,我曾經在 C++ 中找到了一種方法,可以使用引用(如果需要不變性,則為 const 引用)按“真”類型傳遞數組:

#include <iostream>

void ausgabe1D_A(double (&ary1D)[4]){
    // prove type
    std::cout << "Is it really still an array? "
      << (sizeof ary1D == sizeof (double[4]) ? "Yes! :-)" : "No. :-(")
      << '\n';
    for (int i = 0; i < 4; i++)
        std::cout << ary1D[i] << "  ";
}

int main()
{
    double ary1D[4] = {1.1, 2.2, 3.3, 4.4};
    ausgabe1D_A(ary1D);
}

Output:

Is it really still an array? Yes! :-)
1.1  2.2  3.3  4.4  

coliru 現場演示

實際上,這類似於 OP 的方法,只是我使用引用而不是指針。 考慮到這一點,我認為必須有可能修復 OP 的方法(忽略它的用處)並提出:

#include <iostream>

void ausgabe1D_A(double (*ptr1D)[4]){
    double *p = &(*ptr1D)[0];
    for (int i = 0; i < 4; i++)
        std::cout << p[i] << "  ";
}

int main()
{
    double ary1D[4] = {1.1, 2.2, 3.3, 4.4};
    ausgabe1D_A(&ary1D);
}

Output:

1.1  2.2  3.3  4.4  

coliru 現場演示

等等瞧。

我認為您正在尋找通過使用 & 運算符的方法。 這里是 go。

void print( int (*arr)[4])
{
    int *d = *arr;
    for(int i = 0 ;i <4 ; ++i)
    {
        std::cout<<d[i]<<std::endl;
    }
}
int main()
{
    int arr[] = {1,2,3,4};
    print(&arr);

}

如果您覺得難以理解,請告訴我。

暫無
暫無

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

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