Is it possible to make an array that holds an unsigned int?

6

I'm currently trying to make it where an array holds rgba data (0x00000000 → 0xFFFFFFFF) and when I put a value over 2,147,483,647 it overflows, I'm assuming because of some possible conversion (maybe unsigned → signed).

Here's my code:

int main(int argc, char* args[]) {
    uint32_t *background = new uint32_t[1920*1080];

    background[100] = 0xFF0000FF; //red, 4278190335
    printf("%d, ", background[100]);

    return 0;
}

Here's the output:

-16776961

I'm still somewhat new to C++ so if I'm being oblivious to something please point it out.

c++
asked on Stack Overflow Oct 19, 2018 by Pixel • edited Oct 19, 2018 by Uwe Keim

3 Answers

9

First, a quick note:

uint32_t *background = new uint32_t[1920*1080];

Here, background isn't an array (in the stack), rather, you are allocating memory (containing an array) and saving a pointer to the first element. You will need to delete the memory. In C++, it is much easier to use a std::vector:

// at the top: #include <vector>
std::vector<uint32_t> background(1920*1080);

Which will get deallocated automatically (so you don't have to worry about it). Another option is using an array, but in this case, you better not, because it is quite a lot of memory you have there (8 MiB), which may break your stack.

Now, if you want to use printf to print an unsigned int, you need to use %u (or %x if you want it in hexadecimal):

printf("%u, ", background[100]); // or...
printf("%x, ", background[100]);

However, in your code you are using uint32_t, which is a fixed-with type. For this, you would need to use:

// at the top: #include <cinttypes>
printf("%" PRIu32 ", ", background[100]); // or...
printf("%" PRIx32 ", ", background[100]); 

Further, a final note as @Someprogrammerdude commented, you can use std::cout in C++ instead:

// at the top: #include <iostream>
std::cout << background[100] << std::endl; // or...
std::cout << std::hex << background[100] << std::dec << std::endl;
answered on Stack Overflow Oct 19, 2018 by Acorn • edited Oct 19, 2018 by Acorn
7

Change this:

printf("%d, ", background[100]);

to this:

// #include <cinttypes>
printf("%" PRIu32 "", background[100]);

since you want to print a uint32_t, not an int.

PS: Since this is C++, I strongly suggest using std::cout, which will take care automatically for these issues.

PPS: Since you used new [], don't forget to delete [] afterwards.

answered on Stack Overflow Oct 19, 2018 by gsamaras • edited Oct 19, 2018 by gsamaras
0

It is important to understand the difference between numeric data and its representation when you output it. There is no overflow here. The data is just being printed as a signed value. You are assigning it correctly with the hex literal. You should also print it out as hex rather than as decimal.

answered on Stack Overflow Oct 19, 2018 by Code-Apprentice

User contributions licensed under CC BY-SA 3.0