我正在测试以下代码,但是执行时会在这一行中出现 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/