0
int array1[4], array2[4] = {3, 6, 9, 12};
array1 = array2;

and this one:

void showValues (int nums [4][])
{
  for (rows = 0; rows < 4; rows++)
    for (cols = 0; cols < 5; cols++) // is this the line of error? cols is not declared for a size.
        cout << nums[rows][cols];
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Alex Edwards
0

You cannot assign (the contents of) one array to another with a simple assignment statement. You have to write code that assigns from array2 to array1 element by element.

In your function, the parameter must give the column dimension (second set of [ ] ), the row dimension doesn't matter. Since the number of rows can vary, it's typical to pass the row dimension as an additional parameter. Thus, you can write the function so that it can deal with array of any number of rows. Like this:

void showValues (int nums [ ][5], int n_rows )
{
   int r, c;
   for( r = 0; r < n_rows; r++ )
      for( c = 0; c < 5; c++ )
         cout << nums[r][c] << "  ";
}
0
int array1[4], array2[4] = {3, 6, 9, 12};
array1 = array2;

and this one:

void showValues (int nums [4][])
{
  for (rows = 0; rows < 4; rows++)
    for (cols = 0; cols < 5; cols++) // is this the line of error? cols is not declared for a size.
        cout << nums[rows][cols];
}

In your first chunk of code, you could omit the 4 from the declaration of array2.

But the real issue is that array2 is a reference variable that cannot hold a variable amount of addresses. It cannot play the role of a pointer.

Although C++ treats arrays as pointers, they are more or less pointer * const types.
For example...

int val[4]; // array declared on the stack - cannot point to another address
int* const val2 = val; // declares a pointer thats contents can be modified but can only point to one address

in your second chunk of code, neither rows nor cols are declared inside your method, but they are assigned and used. I guess this is fine if they are global variables, but it isn't a best practice.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.