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; } } } 
5
  • Your array looks like one dimentional Commented Feb 4, 2016 at 20:47
  • pname is not a 2d Array it is a char* Commented Feb 4, 2016 at 20:47
  • Why do you want to take a pointer to name? That might help with a more substantial answer. Commented Feb 4, 2016 at 20:50
  • @ForeverStudent pname is supposed to be a pointer to my 2 D array. Commented Feb 4, 2016 at 20:50
  • 1
    Why not just use name[x][y]? What is the pointer usage supposed to do for you? Commented Feb 4, 2016 at 20:51

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Tomyy oh I see.. Thank you!
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.

Comments

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

Comments

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

1 Comment

Answers the question by changing the parameters of the question and then answering the new question. Very Kobayashi Maru.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.