Miguel Wang
Miguel Wang

Reputation: 385

What are the differences when casting from integer to char array in following ways in C?

I am casting from integers to char arrays in the following ways, but I don't understand what are the differences when using print (since in both I am printing char arrays?):

// The desired output is always "65" literal and NOT "A"
// First way:
char a = (char)65;
printf("%d", a); // "65"


// Second way:
char str[3];
sprintf(str, "%d\n", 65);
printf("str: %s\n", str); // "65"

However, the following ways return errors:

// Note that I am exchanging only the format in the printf function
printf("%s", a); // Error
printf("str: %d\n", str); // Error

Upvotes: 1

Views: 44

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You are using invalid conversion specifiers for objects outputted in calls of printf.

In this call

printf("%s", a);

the conversion specifier %s expects an argument of the type char * while you are passing an object of the type char.

In this call

printf("str: %d\n", str);

the conversion specifier %d expects an argument of the type int while you are passing an expression of the type char * to which the array designator is implicitly converted.

As for example for this code snippet

char a = (char)65;
printf("%d", a);

then here is the casting of the integer constant 65 to the type char is redundant.

You may write

char a = 65;

In the call of printf you are using the conversion specifier %d that outputs the character as an integer. That is it outputs the internal representation of the ASCII character 'A'. If you will use the conversion specifier %c instead of %d you will get as the output the symbol 'A'.

Upvotes: 2

Related Questions