Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't one use pointer to char pointers instead of array of char pointers?

Tags:

c

pointers

When I try the second option in the following code to initialize names, I get a segmentation fault. I guess there is something conceptually incorrect with the second option. Any ideas?

 char *names[] = {
            "Alan", "Frank",
            "Mary", "John", "Lisa"
        };

 char **names = {
            "Alan", "Frank",
            "Mary", "John", "Lisa"
        };
like image 832
stressed_geek Avatar asked Jun 06 '12 11:06

stressed_geek


People also ask

Is a char pointer the same as a char array?

Can you point out similarities or differences between them? The similarity is: The type of both the variables is a pointer to char or (char*) , so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer.

Can a pointer can point to an array?

Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.

Why would you use an array of pointers to pointers?

An array of pointers is useful for the same reason that all arrays are useful: it lets you numerically index a large set of variables. Below is an array of pointers in C that points each pointer in one array to an integer in another array. The value of each integer is printed by dereferencing the pointers.

Can pointer be char?

A pointer may be a special memory location that's capable of holding the address of another memory cell. So a personality pointer may be a pointer that will point to any location holding character only. Character array is employed to store characters in Contiguous Memory Location.


2 Answers

Yes. In first case, you have an array of pointers. Each pointer points to a separate item(Alan, Frank...)

The second declaration

char **names;

implies that names is a pointer to a pointer[You cannot initialize a set of strings like this]. As in

char *str = "hello"
char **names = &str;
like image 164
Manik Sidana Avatar answered Sep 19 '22 05:09

Manik Sidana


It has a completely different memory layout.

Your first example is an array of pointers. It occupies 5 times the size of a char *.

Your 2nd example, however, is a pointer to a location where one or more char * are to be expected. It is not possible to initialize it the way you do it.

like image 20
glglgl Avatar answered Sep 20 '22 05:09

glglgl