为什么这段代码修改一个字符串不工作? [英] Why does this code to modify a string not work?
问题描述
对于c风格字符串,如何将字符指定给字符指针指向的内存地址?例如,在下面的示例中,我想将num更改为123456,因此我尝试将p设置为0所在的数字,并尝试用4覆盖它。非常感谢。
With c-style strings, how do you assign a char to a memory address that a character pointer points to? For example, in the example below, I want to change num to "123456", so I tried to set p to the digit where '0' is located and I try to overwrite it with '4'. Thanks.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* num = (char*)malloc(100);
char* p = num;
num = "123056";
p = p+3; //set pointer to where '4' should be
p = '4';
printf("%s\n", num );
return 0;
}
推荐答案
,因为行:
num = "123056";
更改 num
内存(和 p
仍然指向那个内存,所以它们不再是同一个位置)到最可能的只读内存。
changes num
to point away from the allocated memory (and p
remains pointing to the that memory so they're no longer the same location) to what is most likely read-only memory. You are not permitted to change the memory belonging to string literals, it's undefined behaviour.
您需要以下内容:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
char *num = malloc (100); // do not cast malloc return value.
char *p = num;
strcpy (num, "123056"); // populate existing block with string.
p = p + 3; // set pointer to where '0' is.
*p = '4'; // and change it to '4'.
printf ("%s\n", num ); // output it.
return 0;
}
这篇关于为什么这段代码修改一个字符串不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!