char * string1 = malloc(sizeof(char));
char * string2 = malloc(sizeof(char));
string1 = "hello";
string2 = "world";
string1 = string2; // error in the future code
char * string1 = malloc(sizeof(char));
Do not do that. That allocates space for a single character and sets string1
to point to that space. That is almost never useful in a program. Usually, you want to set a char *
to point to more space than a single character, because you are going to work with more than a single character. Or you can set string1
to be NULL
, which indicates it does not currently point to anything.
char * string1 = malloc(sizeof(char));
char * string2 = malloc(sizeof(char));
string1 = "hello";
This causes a “memory leak,” meaning that the program has lost track of the memory allocated by malloc
.
A string literal such as "hello"
is in effect an array of char
that exists for the entire time the program is running. When used in an expression like this, it is automatically converted to a pointer to the first character of that array. So string1 = "hello";
sets string1
to the address of that character. This causes it to forget about its previous value, from malloc(sizeof(char))
.
string1 = string2; // error in the future code
This may or may not be wrong. It sets string1
to point to the same place as string2
. So string1
and string2
will then be pointing to the same string, so they are of course pointing to equal strings, since the string equals itself.
Sometimes when working with pointers to char
, we want to change the pointer to point to a different string, but sometimes we want to copy a string from one place to another. So, whether string1 = string2;
is the right thing for your program depends on what you are trying to do. You would need to provide much more information in your question about the context and what you are trying to do in your program.