C++: Getting hex unexpectedly when printing array
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 withou开发者_运维百科t it everything works fine.
You may have written a std::hex to the cout at some point; 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
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.
精彩评论