【问题标题】:Why does my function print an address instead of the contents of my array?为什么我的函数打印地址而不是数组的内容?
【发布时间】:2015-03-13 15:18:19
【问题描述】:

我的代码应该删除指定的值并移动数组。当我运行代码时,它会打印一个地址而不是数组的内容。我的代码有什么问题?

using namespace std;
void arrayShift(int arr[], int length, int value) {
  for(int i = 0; i<length; i++) {
    if(arr[i] == value) {
      for (int k = i; k<length-1 ; k++) {
        arr[k] = arr[k+1];
      }
      arr[length-1] = 0;
      i--;
    }
  }
  cout << arr;
}

int main() {
  int inputarr[]={9,8, 9, 9, 9, 9, 6};
  int length = 7;
  int value = 9;
  arrayShift(inputarr,length,value);
}

【问题讨论】:

  • 不清楚您要做什么。如果你指定了 void...,你不能指望你的函数返回你的数组
  • 对不起,我刚刚编辑了它
  • void 函数是不返回任何内容的函数。所以...你的意思是用哪个词代替return?
  • 不返回,只是调用
  • Printing an array in C++?的可能重复

标签: c++ arrays void shift


【解决方案1】:

线

cout << arr;

显示地址,因为 cout 不直接显示数组。

您应该使用 for 来显示所有值。类似的东西:

for(int i = 0 ; i < length ; i++)
    cout << arr[i];

但是你真的应该把输出(for with cout)放在主函数中。

【讨论】:

  • 当我进行更改时,我的代码仍会打印地址。
  • cpp.sh/7rbv 我调用它的方式似乎有误。为什么我不能只是 cout 我的功能?
  • 你的函数返回 void,即什么都没有。 cout 将尝试显示您的函数将返回的内容,因此 cout 将尝试不显示任何内容。
  • 那么调用函数的正确方法是什么?
  • 正确的方法是显示你的数组,而不是你的函数返回什么。请参阅:cpp.sh/7mld
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多