c++ - 将 char* 转换为 int 并转换回相同的 char 数组

标签 c++ c

基本上,我试图增加 port 的 int 值。这应该很容易,但我有点卡住了。

它编译很好,但是当我运行它时出现了这个错误: 访问冲突写入位置 0x001f5834

#include "stdafx.h"
#include "iostream"

using namespace std;
#define TESTING "5002"
int main()
{
    char* port = TESTING;
    int portint;
    sscanf ( port, "%d", &portint );
    portint++;
    cout << portint << endl; // it works fine up to here, it prints 5003
    sprintf ( port, "%d", portint);
    return 0;
}

最佳答案

默认情况下,编译器将字符串文字视为不可变的,并且尝试修改其中一个内容会导致运行时发生访问冲突错误,因为这些字符串被放入代码段,并且是只读的。在您的情况下, TESTING 是一个字符串文字,您不能不更改它的值。尝试:

 char port[] = "5002";

与此同时,编译器应该对此发出警告:当您将 const char* 类型分配给 char* 类型时。

MS C++ 编译器有一个编译器选项:Zc:strictStrings .

关于c++ - 将 char* 转换为 int 并转换回相同的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23142694/

相关文章:

c++ - 为什么我年龄不正确

c++ - 使用 clang 和 gcc 编译时代码不调用 Move 构造函数

c++ - 在 Python 中扩展的 C++ 类中的段错误回调问题

c - 如何更改以下 Makefile 以使其适用于 MacOS?

c - fopen 用于读取/写入文件夹 C 中的多个文件

c++ - Windows Mobile WAP 唤醒

c++ - 根据特定数据过滤 std::set

c - (*++argv)[0] 和 while(c = *++argv[0]) 的区别

c++ - volatile 和多线程?

c - 如何从由 iso_c_binding 的 Fortran 调用的 C 函数接收字符串?