in Programming in C edited by
1,132 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.
in Programming in C edited by
by
1.1k views

2 Comments

%d is used to print signed values and %u for unsigned values..
0
0
edited by
thanks
0
0

1 Answer

1 vote
1 vote

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

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true