数组的行为不符合我的预期

时间:2019-11-15 06:08:59

标签: c++ arrays pointers function-pointers

指针仍然让我有些困惑。我希望split函数将一个数组的负元素复制到一个新数组中,并将正元素复制到另一个新数组中。一个不同的函数打印变量。我已经包含了该功能,但我不认为这是问题所在。打印数组时,所有元素均为0:

Enter number of elements: 5   
Enter list:1 -1 2 -2 3
Negative elements:
0 0 
Non-Negative elements:
0 0 0 

我认为问题是在下面的split函数中,我需要以不同的方式传递参数。我尝试使用“ *”和“ **”(不带引号)来传递参数,但收到错误消息,我这样做可能不正确。

void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
  int a = 0;
  int b = 0;  
for (int i = 0; i < aSize; ++i) {
  if (alpha[i] < 0) {
    alpha[i] = bravo[a];
    ++a;
  }
  else {
    alpha[i] = charlie[b];
    ++b;
  }   
}
 if (a + b != aSize) {
   cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
   exit(0);
 }
}

我的主要功能(所有数组都必须是指针):

int num_elements;
  cin >> num_elements;
  int * arr1 = new int[num_elements];
  int x;
  cout << "Enter list:";
  for (int i = 0; i < num_elements; ++i) {
    cin >> x;
    arr1[i] = x;
  }
  int y = 0;
  int z = 0;
  count(arr1, num_elements, y, z);
  int * negs = new int [y];
  int * nonNegs = new int[z];
  split(arr1, negs, nonNegs, num_elements, y, z);
  cout << "Negative elements:" << endl;
  print_array(negs, y);
  cout << endl;
  cout << "Non-Negative elements:" << endl;
  print_array(nonNegs, z);
  cout << endl;

所有功能:

void count(int A[], int size, int & negatives, int & nonNegatives) {
  for (int i = 0; i < size; ++i) {
    if (A[i] < 0) {
     ++negatives;
    } 
    if (A[i] >= 0) {
     ++nonNegatives;
    }
  }
}

void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
  int a = 0;
  int b = 0;  
for (int i = 0; i < aSize; ++i) {
  if (alpha[i] < 0) {
    alpha[i] = bravo[a];
    ++a;
  }
  else {
    alpha[i] = charlie[b];
    ++b;
  }   
}
 if (a + b != aSize) {
   cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
   exit(0);
 }
}


void print_array(int A[], int size) {
  for (int i = 0; i < size; ++i) {
      cout << A[i] << " ";
  }
}

感谢所有帮助。

编辑:对于我不清楚的问题,我深表歉意,我想知道如何使我的数组表现出我想要的样子。

1 个答案:

答案 0 :(得分:0)

数组按照指令:)正确运行,您在split函数中犯了小错误(可能被忽略)。我已注释掉该语句并给出了问题原因,请更正这两行代码,其余都可以。

void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
  int a = 0;
  int b = 0;  
for (int i = 0; i < aSize; ++i) {
  if (alpha[i] < 0) {
    //alpha[i] = bravo[a];// here alpha is your source array, don't overwrite it
    bravo[a] = alpha[i];
    ++a;
  }
  else {
    //alpha[i] = charlie[b];// here alpha is your source array, don't overwrite it
    charlie[b] = alpha[i];
    ++b;
  }   
}
 if (a + b != aSize) {
   cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
   exit(0);
 }
}