-2

I'm having an issue creating a pointer to a multidimensional list. In the case of the single array - no problems output is as it should be. In the case of the multidimensional array - an error message is generated.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    const int ROWS = 3, COLS = 4;
    int list[ROWS][COLS] = { {4, -3, 5, 6}, {5, 1, 7, 2},{-4,6,10,-8}};
    int list2[] = {3, 6, 9, 2};

    int *plist = list;
    int *plist2 = list2;

    for (int row = 0; row < ROWS; row++)
    {
        for (int col = 0; col < COLS; col++)
            cout << setw(4) << list[row][col] << " ";

        cout << endl;
    }

    cout <<  *plist  << endl;
    cout <<  *plist2  << endl;
    return 0;
}

main.cpp:11:14: error: cannot convert "int ()[4]" to "int" in initialization
int *plist = list;

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
YelizavetaYR
  • 1,611
  • 6
  • 21
  • 37
  • There's no pointers-to-array involved in this code whatsoever. There are only a 1D and a 2D array of `int` and a pointer to `int`. The 1D array decays into `int *` so it can be assigned to `plist`. The 2D array decays into a pointer-to-array (`int (*)[COLS]`) and that is incompatible with `int *`. You could write `int *plist = list[0];` or `int *plist = &list[0][0];` instead. – The Paramagnetic Croissant Oct 15 '14 at 20:12
  • 1
    The line `int *plist = list;` simply doesn't make sense, and your compiler is doing the best it can to tell you. `list` is an array of arrays of int, and so it decays to a pointer to the first element, i.e. a pointer to an array of ints, and not a pointer to an int. Plain as midnight. – Kerrek SB Oct 15 '14 at 20:14
  • Better: `for (auto const & row : list) { for (int v : row) { std::cout << v << ' '; } std::cout << '\n'; }` – Kerrek SB Oct 15 '14 at 20:15
  • when you want to reference variables in an array (single dimension) you specify the pointer and set it equal to the array name - saying this is the memory location where this array begins point here. I want to do the same thing with a two dimensional array. start here/point here. that is all. – YelizavetaYR Oct 15 '14 at 20:15
  • @YelizavetaYR Then go with `int (*plist)[COLS] = list;`. – The Paramagnetic Croissant Oct 15 '14 at 20:16
  • Thank you I will. Not sure why this is a bad question but glad to have it straitened out. – YelizavetaYR Oct 15 '14 at 20:43

1 Answers1

1

It really depends on what you are trying to do, but a 2D array cannot decay to a single pointer. As an example, pointer to array would work, letting the first dimension decay to pointer:

int (*plist)[COLS] = list;

You can then access the elements as plist[i][j].

Also beware of using names such as list, especially if you do something adventurous such as saying using namespace std;.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480