1
void func(char a, int num)
{
    printf("%c",a);
}

int main()
{
     func("a", 6); //not func('a',6);
     printf("\n");
     func("b", 2); //not func('b',6);
}

I understand I am passing a char array of a and b with a null character \0. Could someone how it ends up printing the characters $ and &?

1
  • It doesn't compile for me. What compiler lets that all through? Commented Oct 31, 2012 at 6:14

2 Answers 2

4

It could end up printing anything pretty much, probably part of the adresses of "a" and "b" match the ascii code of $ and &.

Sign up to request clarification or add additional context in comments.

3 Comments

How would that happen consistently? I tested across several computers, why would it print the same set of values everywhere?
@Cthulhu, Forgive me if this is completely wrong, but from my experiences with Windows, applications usually have a base address of 0x400000, so if that and endianness were kept constant across computers, they could all print the same thing. There's never really any telling with UB, though.
@chris I didn't know that. Tested on CentOS. Different characters indeed. Thanks! I'll look into the common base-address thing.
2

You are passing pointer to a literal string but the func expects a character. Change it to receive an array:

void func(char *a, int num)
{
    printf("%c",a[0]); // also note that to print a char you need to
                       // 'select' a char from the array
}

Otherwise you'll end up printing to a char that is the ascii representation of whatever the address of a has as the first byte.

3 Comments

I realize what is happening. My question was regarding why it prints those exact characters.
they are random characters based on the address of those strings. If you compile this in a different machine (or use different compilation options) you may get some different characters.
Seems to be the same across all Windows machines, but yes, different ones on other operating systems. @chris has explained in his comment why.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.