简体   繁体   English

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

[英]C++: Getting hex unexpectedly when printing array

I am declaring an array using new 我正在声明一个使用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. 另一方面,当我不使用new&initialize数组时,一切正常。

You may have written a std::hex to the cout at some point; 您可能在某个时候向cout写了一个std :: hex; that will remain in effect until overridden. 它会一直有效直到被覆盖。

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. 数字打印为十六进制值,而不是十进制值。

Try: 尝试:

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

It's still set in hex mode. 仍设置为十六进制模式。

17 2b 2d 4c 22 55 22 61 2d 16 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. 如果将它们打印为小数,将得到23、43等的IOW,恰好是您放入数组中的数字。 Some piece of your code executed prior to your PrintElements() apparently changes the formatting to output hexadecimal numbers. 在您的PrintElements()之前执行的某些代码显然会更改格式以输出十六进制数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM