C - char array and char pointer -
why can't define array
char **pp={ "123", "456", "789" };
but can define char*[] ,and send function accept char **
char *pp[]={ "123", "456", "789" }; fun(pp); void fun(char **pointertopointer) { //++(**pointertopointer);//error printf("%s", *pointertopointer); } //output::"123"
and why can't increment
++(**pointertopointer);
to answer first question, principles might clearer if use single depth of pointer. code illegal same reason:
int *ptr = { 1, 2, 3 };
in c, braced initializer list not object (especially not array). can taken list of items read initializers when object being initialized.
ptr
1 object, @ 1 initializer taken, , expected form of initializer pointer (which 1
not).
in fact code explicitly illegal under c11 6.7.9/11:
the initializer scalar shall single expression, optionally enclosed in braces
however, there gcc bug/feature permits excess initializers scalar , ignores them. further, compilers may "be helpful" , "only" issue warning, , initialize ptr
point address 1
, wherever might be.
"scalar" means object that's not struct or array.
since c99 can write:
int *ptr = (int []){1, 2, 3};
which creates array (using same storage duration ptr
) , points ptr
@ first element.
this array mutable; non-mutable 1 use int const *ptr = (int const[]){1, 2, 3};
instead.
replacing int
char *
, see write:
char **p = (char *[]){ "123", "456", "789" };
in case the pointers in array mutable, things point (i.e. string literals) still aren't.
note should use char const *
when dealing string literals, because not mutable. fact string literals have type char [n]
historical hangover before const
added c. so:
char const **pp = (char const *[]){ "123", "456", "789" };
or non-mutable pointers strings:
char const *const *pp = (char const *const []){ "123", "456", "789" };
Comments
Post a Comment