Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

not understanding folowing C CODE...

Status
Not open for further replies.

suma_ranga

Newbie level 5
Joined
Dec 15, 2011
Messages
10
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Bangalore
Activity points
1,341
hi all,

i have a doubt in the following c code..the output of the code is 20 and 276... can anyone explain y this is so. what is happening in each step. y (int)n = 276 instead of 256..

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
int n = 256;
int *p = &n;
char *pp = (char*)p;
*pp = 20;


pp= printf("%d", (int)*pp);
n =printf("%d", (int)n);
system("PAUSE");
return 0;
}
 

When N is defined as an integer, it is made up of 16 bits. 256 is (0000 0001 0000 0000) in binary.

char *p refers to the first 8 bits starting at the beginning memory location of N, (0000 0001). When you define *pp as (char *)p, you are pointing to the next 8 bits AFTER *p, so it points to the last 8 bits of N, which are (0000 0000).

When you write 20 (0001 0100) to *pp, you overwrite the lower 8 bits of n, so the whole memory space now looks like (0000 0001 0001 0100). The top 8 bits are untouched (which is the only bit needed to represent 256), but the lower 8 are now the bit pattern for 20. So, if you put them all together, you have bits enabled for 256, 16, and 4... sum them up (if you interpret n as a 16-bit interger), you get 276.
 

Hi buddy,

Thank u so much.. very clearly u have explained. thnk u....


When N is defined as an integer, it is made up of 16 bits. 256 is (0000 0001 0000 0000) in binary.

char *p refers to the first 8 bits starting at the beginning memory location of N, (0000 0001). When you define *pp as (char *)p, you are pointing to the next 8 bits AFTER *p, so it points to the last 8 bits of N, which are (0000 0000).

When you write 20 (0001 0100) to *pp, you overwrite the lower 8 bits of n, so the whole memory space now looks like (0000 0001 0001 0100). The top 8 bits are untouched (which is the only bit needed to represent 256), but the lower 8 are now the bit pattern for 20. So, if you put them all together, you have bits enabled for 256, 16, and 4... sum them up (if you interpret n as a 16-bit interger), you get 276.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top