1

I created a 2D array, and made a pointer to point to the first element. I'm trying to print the 2D array, using the pointer but I'm getting the following error. Not sure what I'm doing wrong here.

source_file.cpp: In function ‘int main()’: source_file.cpp:15:27: error: invalid types ‘char[int]’ for array subscript cout << pname[x][y] << endl;

                       ^

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

int main()
{
    char name[2][2] = {'E', 'f', 'g', 'r'};
  char* pname = &name[0][0];

  for (int x = 0; x<2; x++)
  {
    for (int y = 0; y<2; y++)
      {
        cout << pname[x][y] << endl;  
      }  
  }
}
rose
  • 657
  • 2
  • 10
  • 20

4 Answers4

5

pname is a pointer to char. So pname[x] is a char. Therefore pname[x][y] is an attempt to take the yth item from a char, just as if you'd typed char t; t[10];.

Assuming you want to pass a pointer because you want to pass by reference, you want to take an argument of char pname[][10].

If you just want to output the items linearly, use your current pname and step along for(int c = 0; c < 4; c++) cout << pname[c] << endl;.

Tommy
  • 99,986
  • 12
  • 185
  • 204
2

What's happening here is, the char* type drops the array size information from the C-style 2-D array name. Because pname is just a char*, its users have no way of knowing the size and shape of the thing it's pointing to.

comingstorm
  • 25,557
  • 3
  • 43
  • 67
1

I would use something like:

  #define x_size 2
  [...]
  char (*pname)[x_size] = &name[0];

  for (int x = 0; x<2; x++)
  {
    for (int y = 0; y<2; y++)
      {
        cout << pname[x][y] << endl;  
      }  
  }

or:

  int x_size = 2;
  char* pname = &name[0][0];

  for (int x = 0; x<2; x++)
  {
    for (int y = 0; y<2; y++)
      {
        cout << pname[x*x_size + y] << endl;  
      }  
  }
Kite
  • 651
  • 6
  • 16
0

Do this:

int main() {
    char name[2][2] = {{'E', 'f'}, {'g', 'r'}};
    char pname[2][2];
    memcpy(pname, name, sizeof (char)*2*2);

    for (int x = 0; x<2; x++) {
        for (int y = 0; y<2; y++) {
            cout << pname[x][y] << endl;  
        }  
    }
}

It would output: E f g r with newlines inbetween

look up memcopy here

Community
  • 1
  • 1
SegFault
  • 2,526
  • 4
  • 21
  • 41
  • Answers the question by changing the parameters of the question and then answering the new question. Very Kobayashi Maru. – user4581301 Feb 04 '16 at 21:00