can't change array vars

Below in change_array function I am trying to take an existing already initialized array and assign it new values. I am trying to experiment whether the array alterations will behave in a pass by value or pass by address manner but the error below has stopped progress. I just need to know how to change the values all at once instead of one at a time. Thx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>

change_array(int array[], const int length)
{
	error-->array[5] = {3,2,5,6,7};
}

void print_array(int * n_ptr, int length)
{
	for (int i = 0; i<length; ++i)
	{
		std::cout<<*n_ptr<<" ";
		++n_ptr;
	}
}

int main()
{
	const int length = 5;
	int my_array[5] = {3,6,4,5,7};
	int * n_ptr = my_array;
	print_array(n_ptr, length);
	n_ptr = my_array;
	change_array(n_ptr, length);
	return 0;
}


.\src\main.cpp:5:11: error: cannot convert '<brace-enclosed initializer list>' to 'int' in assignment
I just need to know how to change the values all at once instead of one at a time.


Nope. You can make a whole new array all at once, but with an existing array you've got to set each element individually.
Thx --
You could write a small amount of code to copy over the values of a new array; it's an ugly bodge.

1
2
3
4
5
6
7
8
change_array(int array[], const int length)
{  
  int temp[5] = {3,2,5,6,7};
  for (int i = 0; i < length; ++i)
  {
    array[i] = temp[i];
  }
}


or

1
2
3
4
5
change_array(int array[], const int length)
{
  int temp[5] = {3,2,5,6,7};
  memcpy ( array, temp, length * sizeof(int);
}


But really, with an array, if you want one variable to sometimes means that array and sometimes mean this array, consider using a pointer to the first element of the array:
1
2
3
4
5
6
  int* pointer;
  int array1[5] = {3,2,5,6,7};
  pointer = array1;

  int array2[5] = {8,6,7,4,1};
  pointer = array2;
Last edited on
Topic archived. No new replies allowed.