Too many initializer values with unsigned char *?

Hello everyone. I am trying to solve some past papers of my C++ course for practice. There is this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using namespace std;

int main() {
  unsigned char * number_array = { 1, 1, 1 };
	ofstream fs = ofstream("a.out", ios_base::out);
	if (!fs.bad())
	{
		unsigned short * s_p = (unsigned short*)number_array;
		*(++s_p) = 2;
		fs.write(s_p, sizeof(number_array));
	}
	fs.close();
	return 0;
}


And the exercise asks "What will be written at the file?". Could someone help out?
I know that sizeof(unsigned short) is 2 bytes while sizeof(unsigned char) is 1 byte so IF the program ran it would write 1 1 2?
Also, I have another issue: Is the first line of the code valid? Because I tried running it in VS and I had an error "Too many initializer values" on this line which makes sense because it doesn't seem like a right way to initialize an array. Could someone help me with both questions? Thanks a lot.
Note: At the end of the question, it is remarked at the paper that this specific code has some dangers (aka the teacher knows this is some bad code) and asks what kind of dangers do we see here.
Last edited on
An array requires []:

unsigned char number_array[] = { 1, 1, 1 };

The output depends on the byte order of the underlying system. As well as the size of the types.

Line 9 will be out of bounds because in the case of 1/2 the array needs to be 4 bytes.
Yeah, that's just full of problems.

It looks like line 4 is trying to point number_array at an array of 3 unsigned chars. Line 8 points s_p at the same array. Line 9 pre-increments s_p and then changes what it points to.

On many computers, unsigned short is 2 bytes. Now remember that when you increment a pointer, you increment it by the size of what it points to, line 9 increments the pointer by 2 bytes and then writes an unsigned short (2 bytes) at that location.

Kaboom! that means line 9 is probably writing to the 3rd byte of the array at line 4, AND to the byte that comes after that. This is undefined behavior and the program could do anything at all after this point.

Line 10 doesn't do what it appears to want either. number_array is a pointer, so sizeof(number_array) is the size of the pointer, not the size of the array. The pointer will probably be 4 or 8 bytes, depending on whether you're on a 32 or 64 bit machine.
Thanks so much for your prompt responses! These papers are full of "messed-up" code like this and it has made my brain hurt. Didn't consider the error at line 10...Great point made there.
Thanks again!
Topic archived. No new replies allowed.