0

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.

4 Answers 4

7

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).

2
  • So, it means, value is there in the variable. It's just I am not printing in the rightway. That's why it doesnt display. Is that right?
    – arun
    Nov 17, 2010 at 8:27
  • One more doubt, If I move it to the other memory location, will the exact data (entire hex value) will be moved?
    – arun
    Nov 17, 2010 at 8:27
2

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.

0
1

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.

0
0

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

1
  • Thank you. I am not trying to convert but to copy the memory value.
    – arun
    Nov 17, 2010 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.