Problem with char arrarys

Hi guys , Im not that good at c++ but im learning , What i want to do is make a char array started by 0xe9 and followed by unsigned int address represented in the code by jumpto
lets say the jumpto value is 0x12345678 i want the array to hold E9 87 65 43 21
but the program keep crashing .
1
2
3
char *editbytes ="\0xe9";
char* byteArray = (char*)jumpto;
strcat_s(editbytes+1, 4, byteArray);
Last edited on
Please show more code.

As defined above, "editbytes" is a character array with four characters ('0', 'x', 'e', '9'), not one character 0xe9;
Also, "0xe9" is a const char *, not a char *, so writing to it gives undefined results, most likely that's what's causing the crash.

I imagine you don't want to do "(char*)jumpto" unless you really want the contents of address "jumpto" what you want is jumpto itself, so do "(char*)(&jumpto)"

I'm not familiar with strcat_s, so I can't tell if the signature is okay, but it looks like you might be reading from addres "4" instead of byteArray.

Finally, this smells like C not C++. There're much better and easier ways of doing this in basic C++.

Anyway, here's an ANSI C example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE (5)

int main()
{
	int i = 0;
	int jumpto = 0x12345678;
	unsigned char editbytes[ARRAY_SIZE];
	editbytes[0] = 0xe9;
	memcpy(editbytes + 1, (char*)(&jumpto), ARRAY_SIZE);

	/* test */
	for (i = 0; i < ARRAY_SIZE; ++i)
		printf("%#x ", editbytes[i]);
		printf("\n");
	
	return 0;
}
I meant to write \xe9 not 0xe9 , Thanks for your help it works fine now .
I'm also unclear as to what you're trying to do.

You say that jumpto contains 0x12_34_56_78. That is 4 bytes (8 hex nibbles). I've added underscores to identify byte boundaries.

You also say that you want the resulting array to contain E9_87_65_43 _21. That is E9 plus 4 bytes. Note that you have reversed the order of the nibbles (not just the bytes). Simply copying the bytes using memcpy will keep the nibbles in the same order resulting in E9_12_34_56_78.

Note that in the OP you used strcat_s which is a string concatenate, not a string copy. strcat_s will try to find the end of an existing ASCII string and add the source string after that. Not what you want.

Topic archived. No new replies allowed.