Fall 2018
Instructor: Maryam Asadi
Email: masadia@ce.sharif.edu
Sharif University of Technology
1
Fundamentals of Programming
Session 18
These slides have been created using Deitel’s slides
Fundamentals of Programming Session 18 Instructor: Maryam Asadi - - PowerPoint PPT Presentation
Fundamentals of Programming Session 18 Instructor: Maryam Asadi Email: masadia@ce.sharif.edu 1 Fall 2018 These slides have been created using Deitels slides Sharif University of Technology Outlines Pointers Pointer Operators
Fall 2018
Sharif University of Technology
1
Session 18
These slides have been created using Deitel’s slides
2
Pointers enable programs to simulate call-by-reference and
Pointers are variables whose values are memory addresses.
3
Pointers, like all variables, must be defined before they can be
used.
The definition
int *countPtr, count;
specifies that variable countPtr is of type int * (i.e., a pointer to an integer) and is read, “countPtr is a pointer to int” or “countPtr points to an object of type int.” Also, the variable count is defined to be an int, not a pointer to an int.
The * only applies to countPtr in the definition. Pointers should be initialized either when they’re defined or in an
assignment statement.
A pointer may be initialized to NULL, 0 or an address. A pointer with the value NULL points to nothing.
4
The &, or address operator, is a unary operator that returns
int y = 5;
int *yPtr;
yPtr = &y;
5
The unary * operator, commonly referred to as the
For example, the statement
printf( "%d", *yPtr );
Using * in this manner is called dereferencing a pointer. Figure 7.4 demonstrates the pointer operators & and *.
6
7
8
There are two ways to pass arguments to a function—
All arguments in C are passed by value. Many functions require the capability to modify one or
For these purposes, C provides the capabilities for
In C, you use pointers and the indirection operator to
9
10
11
12
13
What will be the output of the program?
int main() { int i=3, *j, k; j = &i; printf("%d\n", i**j*i+*j); return 0; }
Answer:
14
What will be the output of the program?
int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; }
Answer:
Mello
15
What will be the output of the program?
int main() { int ***r, **q, *p, i=8; p = &i; q = &p; r = &q; printf("%d, %d, %d\n", *p, **q, ***r); return 0; }
Answer:
8, 8, 8
16
What will be the output of the program?
int main() { int x=30, *y, *z; y=&x; /* Assume address of x is 500 and integer is 4 byte size */ z=y; *y++=*z++; x++; printf("x=%d, y=%d, z=%d\n", x, *--y, z--); return 0; }
Answer:
x=31, y=31, z=504
17