【问题标题】:Pointer to array in function in c++c++ 函数中指向数组的指针
【发布时间】:2017-09-15 02:58:19
【问题描述】:

我是 C++ 的初学者。指针让我很困惑。特别是关于如何在函数和数组中使用它。我试图在函数中创建一个指向数组的指针并输出它。但是它一直给我数组的地址而不是值。

void testing(int* arr){
    cout << arr << endl;
}

int main()
{
    int my_arr[]{ 4,7,1 };
    testing(my_arr);

    string y;
    getline(cin, y);
    return 0;
}

我尝试使用testing(&amp;my_arr); 输出值,但它给了我错误:

  • “int (*)[3]”类型的参数与类型的参数不兼容 "int *
  • 'void testing(int *)':无法将参数 1 从 'int (*)[3]' 转换为 'int *'

非常感谢您的帮助!

【问题讨论】:

  • 这个错误告诉你你需要知道的一切。 int* 不是指向 int 数组的指针。
  • 你确定你没有用testing(&amp;my_arr);调用函数吗?这就是错误对我的建议。
  • @KenY-N 您是说int* 与指向 int 数组的 指针 相同吗?你错了。指向 int 数组的指针是 int**int *[],如错误所示。
  • “它一直给我数组的地址而不是值”。那是因为(第一项的地址,与数组的地址相同)是您传递给流的地址。它输出的正是你告诉它输出的内容。要输出数组值,请使用循环。它需要知道项目的数量。
  • 了解decaying

标签: c++ arrays function pointers


【解决方案1】:

要打印数组中的而不是起始地址,您需要使用循环。

#include <iostream>
#include <string>

// note extra param for length of array.
void testing(int* arr, int len){
    for (int i = 0; i < len; ++i)
        std::cout << arr[i] << " ";
    std::cout << "\n";
}

int main()
{
    int my_arr[]{ 4,7,1 };
    testing(my_arr, 3);

    return 0;
}

您无法通过 testing(&amp;my_arr),因为根据您收到的错误消息,&amp;my_arr 的类型为 int (*)[]。那和int*不一样。

【讨论】:

    【解决方案2】:

    为了打印数组,您可以使用数组索引或指针算法。测试函数也可以写成

    void testing(int* arr, int len) {
        for (int ctr = 0; ctr < len; ctr++) {
            std::cout << *(arr + ctr) << std::endl;
        }
    } 
    
    int main()
    {
        int my_arr[]{ 4,7,1 };
        testing(my_arr, 3);
    
        return 0;
    }
    

    【讨论】:

    【解决方案3】:

    testing() 中,您尝试使用没有索引的arr 元素。 这里arr 是该内存的唯一基内存地址。要从那里获得价值,您必须指定索引。

    void testing(int* arr, int len)
    {
        for(int i = 0; i < len; i++)
        {
            cout << arr[i] << endl;
        }
    }
    

    在 main() 中你可以传递一个数组的长度。

    int main()
    {
        int my_arr[]{ 4,7,1 };
        testing(my_arr, sizeof(my_arr) / sizeof(int));
        return 0;  
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      相关资源
      最近更新 更多