Question

I am trying to copy the memory value of int into the char buffer. The code looks like below,

#define CPYINT(a, b) memcpy(a, &b, 4)
............

char str1[4];
int i = 1;
CPYINT(str1, i);
printf("%s",s);

...........

When I print str1 it’s blank. Please clarify.

Was it helpful?

Solution

You are copying the byte representation of an integer into a char array. You then ask printf to interpret this array as a null terminating string : str1[0] being zero, you are essentially printing an empty string (I'm skipping the endianness talk here).

What did you expect ? Obviously, if you wanted to print a textual representation of the integer i, you should use printf("%d", i).

OTHER TIPS

try

printf("%02X %02X %02X %02X\n", str1[0], str1[1], str1[2], str1[3]);

instead.

The binary representation of the integer 1, probably contains leading NULs, and so your current printf statement terminates earlier than you want.

What is your intention here? Right now you are putting arbitrary byte values into the char array, but then interpreting them as a string, as it happens the first byte is probably a zero (null) and hence your print nothing, but in all probability many of the characters will be unprintable, so printf is the wrong tool to use to check if the copy worked.

So, either: loop through the array and print the numeric value of each byte, %0xd might be useful for that or if your intention is actually to create a string representation of the int then you'll need a larger buffer, and space for a null terminator.

Maybe you need convert intger to char* in that way tou can use itoa function link text

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top