c++ - 使用 char* 存储整数

标签 c++ arrays pointers char

我正在尝试将整数转换为存储在 char *s 中的数字字符串。

char* ItoA(int n, char *s){ 
    int mod = n;
    for(int x = 1; x <= sizeof(n) + 2; x++){
        int digit = mod % 10;
        s[x-1] = digit;
        mod = mod / 10;
    }
    return s;
}

void main(){
    int n = 12345;
    char s3;
    // should print 12345
    cout << "\n" << ItoA(n, &s3);
    cin.get();
}

我知道我的符号有问题,因为我一直在 main 中得到一个垃圾数组作为输出。为什么我得到的是垃圾而不是“12345”?

最佳答案

问:为什么我得到的是垃圾而不是“12345”?

你正在使用 &s3 就好像它是一个字符数组。

使用:

int main(){
    int n = 12345;
    char s3[20]; // Use an array of characters large enough to hold the number.
    // should print 12345
    cout << "\n" << ItoA(n, s3);
    cin.get();
}

此外,我不清楚您使用下面的 sizeof(n) 的逻辑是什么:

for(int x = 1; x <= sizeof(n) + 2; x++)

关于c++ - 使用 char* 存储整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28287286/

相关文章:

c++ - SIGSEGV 使用 gdb 时无法获取堆栈跟踪

java - 给定类型的构造函数错误,无法应用

pointers - 向量指针在 openCL 中如何工作

c - 如何仅使用 fread() 和 vsscanf() 包装 fscanf()

android - 适用于 android 的 native c++ 3d 数学/几何库?

c++ - 我们为什么可以这样做:Base * base = new Derived;而我们不能做推导*派生=新基数?

c++ - 快速排序索引问题

java - 如何实现返回 "enumeration"对象的函数?

ios - 如何在 Swift 上使这段代码异步

c - 不透明指针 valgrind