简体   繁体   English

用指针更改C字符串值

[英]Change C string value with pointer

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 我想的是他们两个都是troABCol: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. 我知道我有一个指向字符串(char **)的指针,因为那是在方法内部进行此操作所需要的。

you need to do strcpy(*string, "trololol") instead of *string = "trololol" ;. 您需要执行strcpy(*string, "trololol")而不是*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. 您的解决方案带来了内存泄漏,因为它将malloc()分配的内存指针替换为指向数据的指针,该指针包含预先分配的“ trololol”字符串。

strcpy() copies the pure string pointed to, and instead of stringP = "ABC"; strcpy()复制指向的纯字符串,而不是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). ,您可以执行memcpy(stringP, "ABC", 3)strcpy在末尾附加\\0 ,而memcpy仅复制被告知要复制的数据)。

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 . 您应该查找memcpystrcpy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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