为什么这段代码修改字符串不起作用? [英] Why does this code to modify a string not work?

查看:26
本文介绍了为什么这段代码修改字符串不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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
", num );

    return 0;
}

推荐答案

该代码不起作用,仅仅因为该行:

That code won't work, simply because the line:

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
", num );    // output it.

    return 0;
}

这篇关于为什么这段代码修改字符串不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆