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

  • A+
Category:Languages

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.

 


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; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: