rose
rose

Reputation: 667

How do I print an 2D array by means of a pointer? c++

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;  
      }  
  }
}

Upvotes: 1

Views: 3148

Answers (4)

Tommy
Tommy

Reputation: 100622

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;.

Upvotes: 5

Kite
Kite

Reputation: 649

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;  
      }  
  }

Upvotes: 1

SegFault
SegFault

Reputation: 2546

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

Upvotes: 0

comingstorm
comingstorm

Reputation: 26097

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.

Upvotes: 2

Related Questions