variable declaration

Trying to understand a part of this code:

1
2
3
4
5
    

        char   t[4][4], *p = (char *)t;// this line of code I dont understand
        
      
There are two declarations on that line.

The first is a 2-D array or grid of characters.
 
    char   t[4][4];
That can be also considered as an array of four character strings.

Then a second declaration is a character pointer char * p, this could point to a character string. It is assigned the value t which will be the address of the start if the 2-D array. But the there is a mismatch. A 2-D array isn't a string, hence the need for the cast (char *) which tells the compiler to convert the value to the required type.
 
    char * p = (char *) t; // p points to start of array 


Actually, the cast is undesirable, it disguises possible errors. The correct code could look like this, with no cast:
 
    char * p = t[0]; // p points to first item in the array 


Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
    // Declare array of 4 strings
    char   t[4][4] = { "abc", "123", "xyz", "789" };
    
    // create pointer to first item     
    char * p = t[0];
     
    // output value 
    cout << p << '\n';
}
abc

Ok that makes alot of sense now.
Thank You
Last edited on
Topic archived. No new replies allowed.