How to create a pointer to a 2d character array and then print the output

Viewed 363
#include <stdio.h>

int main() {
    char map [3][6] = {
            {'a','.','.','.','.','.'},
            {'.','.','.','.','.','.'},
            {'.','.','.','.','.','.'}
    };//Create a new game map
    char* newmap = map;
    printf("%c",newmap); //Print first element
    return 0;
}

The code I have does not work. I am trying to make a pointer to map[3][6] and then be able to print the array from the pointer.

3 Answers

You have a misconception about pointers and arrays. When you declare:

char map [3][6];

You have declared an array of char[6] arrays (e.g. an array of arrays). To understand what is happening, you have to understand Array/Pointer Conversion governed by C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3)

(p3) Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary '&' operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.

(note: C17 removes _Alignof as an exception)

Applying array pointer conversion, on access map is converted to a pointer of type char (*)[6] (a pointer-to-array-of char[6]). So to use map and newmap as shown, you would need:

char (*newmap)[6] = map;

Then, to output a single character, you would use putchar (**newmap); which would output the first character in the first 6-character array. Pointer arithmetic advances by sizeof (*newmap) (which is an array of char[6]). So putchar (*newmap[1]); would output the first character of the 2nd row in the 2D array.

Multi-Dimensional Array is also stored as a collection of it's Fewer Dimensional Arrays. Two-Dimensional Array is stored as an Array of Single Dimension Arrays.

In the Above Problem, you have two Dimensional Array of map [3][6] which is stored as an Array which stores 3 single-dimensional arrays each of size 6. Thus map [3][6] will return a pointer to a single-dimensional array having 6 elements in its every index.

So a pointer should be like char (*ptr)[6] = map ;

Now we would have a pointer through which we can access the array.

ptr[0] will be ['a','.','.','.','.','.'] and ptr[0][0] will be 'a'

For a clearer explanation, you can watch the pointer series of MyCodeSchool on YouTube.

youtube link to pointer video

#include <stdio.h>

int main() {
    char map [3][6] = {
            {'a','.','.','.','.','\0'},
            {'.','.','.','.','.','\0'},
            {'.','.','.','.','.','\0'}
    };//Create a new game map
    char (*newmap)[6] = map;
   
   for( int i=0;i<3;i++)
   {
     printf("%s\n",newmap[i]); 
   }
    return 0;
}

\0 must be appended to get desired output. As David pointed out char (*newmap)[6] is a pointer to an array of six elements ( char[6]).
The output is:

a....
.....
.....
Related