0

Following code when executed, prints out a smiling face (ASCII equivalent of integer 2), but when the format specifier in printf is changed from %c to %d, it does not print integer 2. Any reasons why....

main()
{       int i;
	int *c; char b[10]={1,2,3,4,5,6,7,8,9,0 };
	c=&b[1];
	printf("\n%c",*c);
}

Edited by Rupindersingh: n/a

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Ancient Dragon
1

You need to type cast

c=(int*)&b[1];

in b you are storing ascii values.
if you are printing it with %c, you will get the the ascii character in that value.
but when it is to be printed with %d, that ascii character doesn't prints garbage value as you are storing the values in integer pointer.
but if you change it to character pointer, it will work ;)

#include<stdio.h>
main()
{     
        char *c; char b[10]={1,2,3,4,5,6,7,8,9,0 };
        c=&b[1];
        printf("\n%d",*c);
}
#include<stdio.h>
main()
{
        char *c; char b[10]={1,2,3,4,5,6,7,8,9,0 };
        c=&b[1];
        printf("\n%c",*c);
}

and you dont need typecasting tooo... ;)

0

No amn, its still not working....
It works only if you use a char pointer.

Edited by Rupindersingh: n/a

1

>>c=&b[1];

It might help if you posted code that compiles. The above line is an error because its trying to convert char* to int*, which can't be done without a typecast.

Next, it displays funny characters because array b[] is an array of binary values, which are not displayable. If you want them to display correctly you need to make them characters, such as char b[] = "'1','2','3','4'};

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.