Chapter 11-p - Example 11.1 Write a program to print the...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Example 11.1 Write a program to print the address of a variable along with its value. The program shown in Fig.11.4, declares and initializes four variables and then prints out these values with their respective storage locations. Notice that we have used %u format for printing address values. Memory addresses are unsigned integers. ACCESSING ADDRESSES OF VARIABLES Program main() { char a; int x; float p, q; a = 'A'; x = 125; p = 10.25, q = 18.76; printf("%c is stored at addr %u.\n", a, &a); printf("%d is stored at addr %u.\n", x, &x); printf("%f is stored at addr %u.\n", p, &p); printf("%f is stored at addr %u.\n", q, &q); } Output A is stored at addr 4436. 125 is stored at addr 4434. 10.250000 is stored at addr 4442. 18.760000 is stored at addr 4438. Fig.11.4 Accessing the address of a variable Example 11.2 Write a program to illustrate the use of indirection operator '*' to access the value pointed to by a printer. The program and output are shown in Fig.11.5. The program clearly shows how we can access the value of a variable using a pointer. You may notice that the value of the pointer ptr is 4104 and the value it points to is 10. Further, you may also note the following equivalences: ACCESSING VARIABLES USING POINTERS
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Program main() { int x, y; int *ptr; x = 10; ptr = &x; y = *ptr; printf("Value of x is %d\n\n",x); printf("%d is stored at addr %u\n", x, &x); printf("%d is stored at addr %u\n", *&x, &x); printf("%d is stored at addr %u\n", *ptr, ptr); printf("%d is stored at addr %u\n", y, &*ptr); printf("%d is stored at addr %u\n", ptr, &ptr); printf("%d is stored at addr %u\n", y, &y); *ptr = 25; printf("\nNow x = %d\n",x); } Output Value of x is 10 10 is stored at addr 4104 10 is stored at addr 4104 10 is stored at addr 4104 10 is stored at addr 4104 4104 is stored at addr 4106 10 is stored at addr 4108 Now x = 25 Fig.11.5 Accessing a variable through its pointer Example 11.3 Write a program to illustrate the use of pointers in arithmetic operations. The program in Fig.11.7 shows how the pointer variables can be directly used in
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 05/14/2010 for the course CS SS ZG653 taught by Professor Shanta during the Spring '09 term at Birla Institute of Technology & Science.

Page1 / 10

Chapter 11-p - Example 11.1 Write a program to print the...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online