I have been trying to figure out how double pointer works with char * and char []. What I want to do is to assign a double pointer to the char * or char [] and then change the content.
#include <stdio.h>
int main()
{
char * message2 = "bye world";
char message[] = "hello world";
char ** ptr_message2 = &message2;
char ** ptr_message = (char*)&message;
*ptr_message2 = "Bye";
*ptr_message = "Hello";
printf("%s \n", message2);
printf("%s \n", message);
return 0;
}
I want to use char[] and assign double pointer to it, and change the content but I have hard time understanding.
In this declaration
there is declared a pointer that points to the first character of the string literal
"bye world". You may reassign the pointer to point to another string as for exampleThe string literals themselves are not changed. It is the pointer that is changed. At first it pointed to the first character of one string literal and then it was reassigned by the address of the first character of another string literal.
This statement
only adds one more indirection. So the above statement
can be rewritten like
Arrays opposite to pointers do not support the assignment operator. If you want to change a content of an array you need to change its elements separately. For example to copy a string to a character array you can write
As for your code then after this declaration
the pointer
ptr_messagestores the address of the extent of memory occupied by the array that is the same address as the address of the first character of the array.Dereferencing the pointer
the value stored in the first elements of the array is considered as a value of an address. As the stored string
"hello world"does represent a valid address then the dereferenced pointer has an invalid value and the statement above invokes undefined behavior.Using a pointer to pointer you could write for example by introducing an intermediate pointer the following way
Now dereferencing the pointer
ptr_messageyou get another pointer (instead of characters of a string literal) that points to the first character of the array and may use it to change elements of the array.Pay attention to that in these declarations
and
the arrays (string literals have types of character arrays) used as initializers are implicitly converted to pointers to their first elements.