How To Initialize Array Of Ints As String Literal


I am attempting to initialize an array of ints as a string literal. So far, this is what I have.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

union {
	char Chars[];
	unsigned int ints[];
} _u={(char[]){*"\x000000FF0000000F"}};

int main( void ) {
	std::cout << _u.ints[0] << "\n"		// Should output 255
		   << _u.ints[1] << "\n";	// Should output 15
}


But, I absolutely cannot initialize it as something like {0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x0F} because the actual array I will be using will be 32MB big (as in how much memory it will take up after the program is run), so compression is crucial for reducing compile time.
Last edited on
That seems like an exceedingly bad idea.

Why is compilation time "crucial?" (And what makes you think this would help - I would imagine it's more likely to increase compile time than reduce it.)

There are several things wrong with your code. "\x000000FF0000000F" gives you a single byte.
See: http://stackoverflow.com/questions/24521837/stdstring-control-characters-assigning-a-hex-number-to-a-string

In C++, arrays must have sizes specified (lines 4 and 5). Dereferencing a string literal as you do on line 6 gives you a character. One hopes your compiler complains when you try to cast the character into a pointer.
Last edited on
This entire snippet with the union is technically wrong (but practically fine). According to the standard, you can only read the type you last wrote.

If your table is that large, you're either computing it beforehand, or copying it from someplace. Why can't your program simply read the data from the source instead of storing a 32MB copy of static garbage in the executable?

If you must do what you say, skip the compiler and let the linker help you. Alternatively, put the initializer in its own source file and compile it once. If you're using a time-aware build script, this shouldn't be an issue, since you won't need to recompile your humongous table all the time.

An example of the first technique can be found here
https://balau82.wordpress.com/2012/02/19/linking-a-binary-blob-with-gcc/
Last edited on
Thank you so incredibly much for your input. You really are incredibly helpful. You really have helped me out a lot, so thank you. Also, thank you for the very helpful links.
Last edited on
Topic archived. No new replies allowed.