edited by
1,138 views
0 votes
0 votes
main()
{
unsigned int i= 255;
char *p= &i;
int j= *p;
printf("%d\n", j);
unsigned int k= *p;
printf("%d", k);
}

 

Both the outputs are -1. I have even tried with - int i = 255(3rd line). Still the output is -1.

I don't understand how it is -1.
edited by

1 Answer

1 votes
1 votes

I guess we saw that happening due to incompatible type casting.

When we use char *p = &i : due to signed / unsigned type casting (underflow) unsigned 255 becomes signed -1 hence the values of j and k.

Try to run below:

int main(){
    unsigned int i = 255;
    int *p = &i;
    int j = *p;
    
    unsigned int k = *p;
    
    printf ("i : %d \n", i);
    printf ("j : %d \n", j);
    printf ("k : %d \n", k);
    
    return 0;
}

Let me know your thoughts. 

Related questions

0 votes
0 votes
1 answer
1
Mr khan 3 asked Nov 3, 2018
982 views
#include<stdio.h void fun(int *p,int *q) { p=q; *p=q; } int i=0,j=1; int main() { fun(&i,&j); printf("%d%d",i,j); }What will be the output of i and j in 16-bit C Compiler...
0 votes
0 votes
0 answers
3
garvit_vijai asked Sep 2, 2018
685 views
Please explain the output for the following program: #include<stdio.h>int main() { int i = 100; int *a = &i; float *f = (float *)a; (*f)++; pri...
0 votes
0 votes
3 answers
4