Professional Documents
Culture Documents
1. Yes! scanf(%d,ptr)
reads input integer into
the box pointed to by Suppose I now add the following
the corresponding statement after above fragment
argument. scanf(%d,ptr); Input
2. The box pointed to by
and input is : 5
ptr is num[1].
3. So num[1] becomes 5. Does num[1] become 5?
num num
[0] num[1] num[2] num[9]
5 Well, what
ptr else can
you do
num is of type int [] (i.e., array with ptr?
of int). In C the box num
stores the pointer to num[0].
Internally, C represents num
and ptr in the same way. So
the type int * can be used
wherever int[] was used.
Whats so
Here are the interesting parts! You can interesting?
1. de-reference the pointer. Please give
2. do simple arithmetic + - with pointers. examples.
3. compare pointers and test for ==, <, >
etc., similar to ordinary integers.
10
num num
[0] num[1] num[2] num[3] num[4] num[9]
5
ptr
str
ptr g i r l \0
str[16] str[20]
ptr points to str[6]. printf prints
the string starting from str[6], which is
Output is a nice girl
OK. Let me understand.The char
array str[] was initialized as below.
Yes,
thats
correct
Pointers play an important role when
used as parameters in function calls.
Lets start with the old example.
int main() { void swap(int a, int b) {
int a = 1, b = 2; int t;
swap(a,b); t = a; a=b; b =t;
printf(From main); printf(From swap);
printf(a = %d,a); printf(a = %d,a);
printf(b=%d\n,b); printf(b= %d\n,b);
} }
The swap(int a, int b) function is
intended to swap (exchange) the
values of a and b.
But, if you remember, the
value of a and b do not
change in main(), although OK, lets first
they are swapped in swap(). trace the call to swap
int main() { void swap(int a, int b) {
int a = 1, b = 2; int t;
swap(a,b); t = a; a=b; b =t;
printf(From main); printf(From swap );
printf( a = %d,a); printf(a= %d,a);
printf(b = %d,b); printf(b= %d\n,b);
} }
b 2
Now swap() returns:
main() 1. Return address is
swap() line 3 of main().
return
main.3 Program counter is
address
set to this
1 location.
a 2
1
2. Stack for swap() is
t deleted.
b 1
2
int main() { void swap(int a, int b) {
int a = 1, b = 2; int t;
swap(a,b); t = a; a=b; b =t;
printf(From main); printf(From swap );
printf( a = %d,a); printf(a = %d,a);
printf(b = %d,b); printf(b = %d\n,b);
} }
Output: From swap a = 2 b = 1
a 1
0x1024 0x2000
ptra
ptrb
t
Simplified View of Memory: Recap
1004000 A
Content of the 4-blocks starting 1004001 E
at address 1004012 1004002 I
1004001 1004003 O
Without knowing the context it is 1004004 U
not possible to determine the
Type 1004006
helps us
1004005
1004001
1004008
1004009
It could be the location of 1004010
1024