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"
};
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.
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.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With