EE171_Lecture_9_Programming_in_C
EE171_Lecture_9_Programming_in_C
Lecture 9:
Computer Programing with C
1
Pointers
2
3
Pointers
4
#include<stdio.h>
int main()
{
int a = 20;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
How to Initialize a Pointer…
13
#include <stdio.h>
int main () {
int age = 20;
int *ptr;
ptr = &age;
printf("Address of age variable: %X\n", &age );
printf("Address stored in ip variable: %X\n", ptr );
printf("The actual value inside *ip: %d\n", *ptr );
}
Pointer and Arrays
16
#include <stdio.h>
int main () {
int arr[3] = { 10, 20, 30 };
printf("Value of first element is : %d \n", arr[0] );
printf("Value of second element is : %d \n", arr[1] );
printf("Value of third element is : %d \n", arr[2] );
}
Accessing array addresses…2
21
#include <stdio.h>
int main () {
int arr[3] = { 10, 20, 30 };
printf("Address of first element is : %d \n", &arr[0] );
printf("Address of second element is : %d \n", &arr[1] );
printf("Address of third element is : %d \n", &arr[2] );
}
Accessing array addresses…3
22
#include <stdio.h>
int main () {
int arr[3] = { 10, 20, 30 };
printf("Address of first element is : %d \n", arr );
printf("Address of second element is : %d \n", arr + 1 );
printf("Address of third element is : %d \n", arr + 2 );
}
Accessing array addresses…4
23
#include <stdio.h>
int main () {
int arr[3] = { 10, 20, 30 };
int *p = arr;
printf("Address of first element is : %d \n", p);
printf("Address of second element is : %d \n", p + 1 );
printf("Address of third element is : %d \n", p + 2 );
}
Accessing array values…5
24
#include <stdio.h>
int main () {
int arr[3] = { 10, 20, 30 };
int *p = arr;
printf("Value of first element is : %d \n", *p);
printf("Value of second element is : %d \n", *(p + 1) );
printf("Value of third element is : %d \n", *(p + 2) );
}
Exercise
25
#include <stdio.h>
int main () {
int arr[5] = { 10, 20, 30, 40, 50 };
int i;
for ( i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
}
Approach 2…
27
#include <stdio.h>
int main () {
int arr[5] = { 10, 20, 30, 40, 50 };
int i, *p = arr;
for ( i = 0; i < 5; i++)
{
printf("%d ", *(p+i));
}
}
Approach 3…
28
#include <stdio.h>
int main () {
int arr[5] = { 10, 20, 30, 40, 50 };
int i, *p = arr;
for ( i = 0; i < 5; i++)
{
printf("%d ", *p);
p++;
}
}
Pointer and Functions
29
Call by Value
Call by Reference
Call by Value
30