How can you determine if a variable is a two-dimensional array, an array of pointers, or double char pointers?

Suppose we have 3 variables:

 char a[4][4];
 char *b[4];
 char **c;

Assume that all of the above variables have correctly assigned values. There are no code errors.

All of these variables can print their values ​​using the [] operator, as shown below:

for( i=0; i<4; i++){
    printf( "%s\n", a[i] );
}
for( i=0; i<4; i++){
    printf( "%s\n", b[i] );
}
for( i=0; i<4; i++){
    printf( "%s\n", c[i] );

Just by looking at these print statements, there is no way to identify its true data types. How to define its variable data types?

, . 2-D . , . ?

+4
4

, , char?

. , "2D-" - .
" char" char **

_Generic().

#define xtype(X) _Generic((&X), \
    char (*)[4][4]: "char [4][4]", \
    char *(*)[4]  : "char *[4]", \
    char ***      : "char **", \
    char (*)[4]   : "char [4]", \
    char **       : "char *", \
    char *        : "char", \
    default       : "?" \
)

int main(void) {
  char a[4][4];
  char *b[4];
  char **c;
  puts(xtype(a));
  puts(xtype(b));
  puts(xtype(c));
  puts(xtype(a[0]));
  puts(xtype(b[0]));
  puts(xtype(c[0]));
  puts(xtype(a[0][0]));
  puts(xtype(b[0][0]));
  puts(xtype(c[0][0]));
}

char [4][4]
char *[4]
char **
char [4]
char *
char *
char
char
char

_Generic() C, . , , , OP .

, _Generic, , a,b,c. _Generic, , , .

#define xtype(X) _Generic((&X), \
    char (*)[][4] : "char [][4]", \
    char *(*)[]   : "char *[]", \
    char ***      : "char **", \
    char (*)[]    : "char []", \
    char **       : "char *", \
    char *        : "char", \
    default       : "?" \
)
+4

, , , . , , - - , ints.

:

.

C . , . , , .

.

, . C11 _Generic . switch, case s, .

C11 Draft, 6.5.1.1

+1

, . ,

&a[0][0] 16, 16 * 2 , , 16 * 4 &a[3][3]

&b[0][0] 4, 4 * 2 4 * 4 b[0][3]

- c

But the investigator should know to use them anyway so that you most likely cannot use them interchangeably without ignoring compile-time warnings.

0
source

Using sizeof(), you can differentiate these variables because it sizeof()will give different sizes for different variables. Hope this helps you.

-2
source

Source: https://habr.com/ru/post/1675114/


All Articles