im trying to change a part of a string using another pointer. what I have
char** string = (char**) malloc (sizeof(char*));
*string = (char*) malloc (100);
*string = "trololol";
char* stringP = *string;
stringP += 3;
stringP = "ABC";
printf("original string : %s\n\n", *string);
printf("stringP : %s\n\n", stringP);
What I get
original string : trololol;
stringP : ABC;
what I whant is troABCol in both of them :D
I know I have a pointer to a string (char**) because thats what I need in order to do this operation inside a method.
you need to do strcpy(*string, "trololol")
instead of *string = "trololol"
;. Your solution brings memory leak, as it replaces the memory pointer allocated by malloc()
with pointer to data, which contains the pre-allocated "trololol" string.
strcpy()
copies the pure string pointed to, and instead of stringP = "ABC";
, you can do memcpy(stringP, "ABC", 3)
( strcpy
appends \\0
at the end, whereas memcpy
copies only data it is told to copy).
Read Amit's answer. Also, when you write
stringP = "ABC";
you are just changing the pointer to point at a different string; you are not changing the string it was pointing at. You should look up memcpy
and strcpy
.
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.