user3035408
user3035408

Reputation: 3

c printing too many chars

I'm trying to print out a memory address backwards like in a little endian machine, but for some reason my program is outputting both char arrays in my program.

char address[8];
char result[16];
scanf("%s", address);
int x = 1;
for(x; x<5; x++)
{
int y = 4*x;
int z = 8 - 2*x;
result[y-4] = '\\';
result[y-3] = 'x';
result[y-2] = address[z];
result[y-1] = address[z+1];
}
printf("%s", result);

for example, if I input "12345678" it outputs "\x78\x56\x34\x1212345678" I want the "\x78\x56\x34\x12", but I don't understand why the "12345678" is also printed.

Upvotes: 0

Views: 354

Answers (2)

tesseract
tesseract

Reputation: 901

%s //

in C %s expects a pointer to a string, unlike %d or %c(these expect variables with integers or characters), so your pointer must be null terminated, so the program knows where in memory it must stop printing, or else your are printing random stuff in memory

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

You forget to terminate the string. In fact, your array is to small for the terminator, you need it to be 17 characters, then do result[16] = '\0';.


Oh, and you have an out-of-bound error in your code as well, as if you enter 8 characters for the input then scanf will write 9 characters to the 8-character array.

Upvotes: 5

Related Questions