c - 将新值分配给 char* 变量时发生访问冲突

标签 c pointers char

我正在测试以下代码,但是执行时会在这一行中出现 AV:

*port = 0;

如何解决?我做错了什么?

#include "stdafx.h"
#include <windows.h>
#include <conio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char *host = "127.0.0.1:1234";
    char *port = strchr(host, ':');

    if (port)
    {
        *port = 0;
        ++port;
        printf("%s \n", *port);

        int portInt = strtol(port, NULL, 10);

        printf("%d: \n", portInt);
    }

    getchar();

    return 0;
}

最佳答案

问题是您正在尝试修改字符串文字 (host)。字符串文字是 const,因此尝试修改一个是未定义的行为。

因为 port 指向字符串文字中的一个字符,尝试通过这样做来修改该值:

*port = 0;

导致未定义的行为,在您的情况下是崩溃。

一个解决方法是简单地使 host 成为一个 char 数组:

char host[] = "127.0.0.1:1234";
char *port = strchr(host, ':');

由于声明已更改为 host 的数组,因此该数组中的所有字符都可以修改。

关于c - 将新值分配给 char* 变量时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756436/

相关文章:

c++ - 将无符号短裤数组转换为无符号字符数组

计算输入中的字符

c - 为什么这一行使我的程序出现段错误?

c - apr apr_time_h 的格式说明符

c - 在 C 中使用 libopus 编码 pcm 并解码 opus 数据

c - 将 memcpy 与 void 指针一起使用时出现段错误 - C

C++ 指向数组返回类型的指针

c - 一次又一次初始化时,指针在循环内做了什么?

c - 如何在 printf() 中使用多个精度?

c++ - 在 C++ 中拆分 const char*