C++:打印数组时意外获取十六进制

发布于 2024-09-12 11:59:37 字数 480 浏览 6 评论 0原文

我正在使用 new 声明一个数组

int *a = NULL;
a = new int[10];

a[0] = 23;
a[1] = 43;
a[2] = 45;
a[3] = 76;
a[4] = 34;
a[5] = 85;
a[6] = 34;
a[7] = 97;
a[8] = 45;
a[9] = 22;

PrintElements(a, 10);

void PrintElements(int * array, int size){
    for (int i=0; i<size; i++) {
        cout << endl << array[i];
    }
}

现在,当我打印值时,我得到这些值

17
2b
2d
4c
22
55
22
61
2d
16

有人可以告诉我我做错了什么......? 另一方面,当我不使用 new &初始化数组没有它一切正常。

I am declaring an array using new

int *a = NULL;
a = new int[10];

a[0] = 23;
a[1] = 43;
a[2] = 45;
a[3] = 76;
a[4] = 34;
a[5] = 85;
a[6] = 34;
a[7] = 97;
a[8] = 45;
a[9] = 22;

PrintElements(a, 10);

void PrintElements(int * array, int size){
    for (int i=0; i<size; i++) {
        cout << endl << array[i];
    }
}

Now when I print the values I am getting these values

17
2b
2d
4c
22
55
22
61
2d
16

Can somebody tell me what am I doing wrong...?
On the other hand when I dont use new & initialize array without it everything works fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

生来就爱笑 2024-09-19 11:59:37

您可能在某个时刻向 cout 写入了 std::hex;这将一直有效,直到被覆盖。

You may have written a std::hex to the cout at some point; that will remain in effect until overridden.

左岸枫 2024-09-19 11:59:37

它与数组的静态或动态分配没有任何关系。

这些数字打印为十六进制值而不是十进制值。

It doesnt have anything to do with the static or dynamic allocation of the array.

The numbers are printed as Hexadecimal values and not decimal values.

无法回应 2024-09-19 11:59:37

尝试:

std::cout << dec << //all your stuff here

仍然设置为十六进制模式。

Try:

std::cout << dec << //all your stuff here

It's still set in hex mode.

单调的奢华 2024-09-19 11:59:37

17 2b 2d 4c 22 55 22 61 2d 16

这些显然是十六进制数。如果将它们打印为小数,则会得到 23、43 等。IOW,正是您放入数组中的数字。在 PrintElements() 之前执行的某些代码显然会更改输出十六进制数字的格式。

17 2b 2d 4c 22 55 22 61 2d 16

These are obviously hexadecimal numbers. If you print them as decimals you get 23, 43, etc. IOW, exactly the numbers that you have put into the array. Some piece of your code executed prior to your PrintElements() apparently changes the formatting to output hexadecimal numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文