I am trying to understand pointer to pointers and I can not understand why in first case I need (&) ampersand ( I receive a message [Error] cannot convert 'char*' to 'char**' in assignment ) and in the second case I don't need ampersand
first case :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *p ={"jack is a good boy"};
char**p1;
p1=p; //why I need & in this case
return0;
}
second case :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *p[5] ={"jack","is", "a","good","boy"};
int i=0;
char**p1;
p1=p;
//p1=&p[0];
for(p1=p; *p1; p1++)
{
printf("\n the words are %s",*p1);
}
return 0;
}
The variable
p
has the typechar *
While the variable
p1
has the typechar **
So you are trying to use incompatible pointer types in the assignment statement.
You need to write
In this case the pointer
p1
will point to the objectp
that has the typechar *
. That is a pointer to the objectp
will have the typechar **
.In the second program you declared an array with the element type
char *
.Array designator used in expressions with rare exception is implicitly converted to pointer to its first element
So in this assignment statement
that is equivalent to
the expression
p
used as an initializer is converted to the typechar **
. So the left and the right operands of the assignment have the same pointer type.Pay attention to that this for loop
invokes undefined behavior because the array
p
does not have a null pointer among its elements. Thus the condition of the for loop*p1
that is the same as*p1 != NULL
will not be evaluated for elements of the arrayp
.If the loop will be correct you need to include an element that is equal to null pointer, For example
or