What is the difference between char *name[10] and char (*name)[10]?

Viewed 1140

I am very confused about what the two notations denotes. I know that the precedence of () is greater than [], does that mean char(*name)[10] is a pointer and char *name[10] is an array?

3 Answers

This declaration

char *name[10];

declares an array of 10 elements of the type char *.

For example such an array can be initialized the following way

char *name[10] = { "Peter", "Tom", "Michael" };

All elements of the array that do not have a corresponding initializer will be implicitly initialized by NULL. That is the above declaration is equivalent to

char *name[10] = 
{ 
    "Peter", "Tom", "Michael", NULL, NULL, NULL, NULL, NULL, NULL, NULL 
};

A pointer to the first element of the array will look like

char **p = name;

A pointer to the whole array will look like

char * ( *p )[10] = &name;

This declaration

char (*name)[10];

declares a pointer to object of the array type char[10].

For example if you have an array declared like

char name_list[][10] =
{
    "Peter", "Tom", "Michael"
};

then you can declare a pointer to the first element of the array like

char (*name)[10] = name_list;

A pointer to the whole array can be declared like

char ( *p )[3][10] = &name_list;

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    {
        char *name[10] = { "Peter", "Tom", "Michael" };

        char **p1 = name;
        puts( *p1 );
        
        char * ( *p2 )[10] = &name;
        puts( ( *p2 )[0] ); 
        // or 
        puts( **p2 );
    }
    
    putchar( '\n' );
    
    {
        char name_list[][10] =
        {
            "Peter", "Tom", "Michael"
        };
        
        char ( *p1 )[10] = name_list;
        puts( *p1 );
        
        char ( *p2 )[3][10] = &name_list;
        puts( ( *p2 )[0] ); 
        // or 
        puts( **p2 );
    }

    return 0;
}

The program output is

Peter
Peter
Peter

Peter
Peter
Peter

int *a[10] - declares an array of 10 pointers to integer.

int (*a)[10] - declares a pointer to the array of 10 integers.

*name[10]

is an array OF 10 pointers. They are usually used when working with 2-dimensional arrays.

(*name)[10]

This on the other hand is basically a pointer TO an array of 10 ints or whatever.

Related