2

Declaring an array

char a[10][20] = {...}

I can't find the right way to create a pointer x so that a[1][3], for example, is x[1][3].

I tried:

// try 1
char * x; x = &a[0][0];
// try 2
char * x; x = a;
// try 3
char ** x; x = a;
// try 4
char ** x; x = &a[0][0];

How do I work this out?

Shoe
  • 74,840
  • 36
  • 166
  • 272

3 Answers3

2

You can say char (*p)[20] = a;, which makes p into a pointer to an array of 20 chars. This means that ++p leaps to the next slice of 20, and you have 10 of those slices (each denoted by the expression p[i], where 0 ≤ i < 10.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • How can I return `p` from a function? How do I set the type of the function that returns p? – Shoe Feb 09 '12 at 20:56
  • @Jeff; `typedef char (*my_array_pointer_type)[20]; my_array_pointer_type forExample() {}` But make sure you [don't forget your bible in the hotel](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794). – R. Martinho Fernandes Feb 09 '12 at 20:59
  • @R.MartinhoFernandes... mmm, ok and where do I place it if the function name is `forExample() {}`? – Shoe Feb 09 '12 at 21:01
  • 1
    @JeffPigarelli: Don't use raw arrays or raw pointers in C++ at all. At all. Take a look at the standard library and use an appropriate container. – Kerrek SB Feb 09 '12 at 21:22
0

The value of a is of type char (*)[20], i.e., the type pointer to an array 20 of char.

You can declare an object x of this type this way:

char a[10][20] = { ... };
char (*x)[20] = a;

x[3][14] = 42;  // you can then access x elements like with a
ouah
  • 142,963
  • 15
  • 272
  • 331
  • Not quite; the type of `a` is `char[10][20]`, which is convertible to `char (*)[20]` where necessary. – Mike Seymour Feb 09 '12 at 20:44
  • @MikeSeymour the type of `a` is `char[10][20]`, the type of the value of `a` is `char (*)[20]`. – ouah Feb 09 '12 at 20:45
  • I don't know what you think you mean by "the type of the value of `a`", but it's still an array. Like all arrays, it can be converted to a pointer when necessary, but it still has the type of an array. – Mike Seymour Feb 09 '12 at 20:52
  • How can I return `p` from a function? How do I set the type of the function that returns `p`? – Shoe Feb 09 '12 at 20:58
0

You can use regular pointer to a bidimensional array this way

int arr[10][20];
int* p = (int*) arr; or p = &arr[0][0];
//the mean to set or get value of the member [i][j]
*(p+20*i +j) = 777;
int a = *(p+20*i+j);
mikithskegg
  • 806
  • 6
  • 10