简体   繁体   中英

How to make assign one char* to the another char*

how to make st1 = st2 if they are both char*

char * string1 = malloc(sizeof(char));
char * string2 = malloc(sizeof(char));
string1 = "hello";
string2 = "world";

string1 = string2; // error in the future code 

how to appropriately make that happen?

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.

Use strcpy() to copy strings.

char *string1 = malloc(6);
char *string2 = malloc(6);

strcpy(string1, "hello");
strcpy(string2, "world");

strcpy(string1, string2);

Make sure you allocate enough space for the longest string you're going to copy, plus an extra byte for the null terminator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM