Pointers in C

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 99

Pointers in ‘C’

Pointers
int a=1,b;
a b

1000 – 1003 2000 – 2003

b = a; // b=1;
b = &a; X &a = 1000
Address can only be stored in pointer variable.

2
Pointers
Definition:
A variable which is capable of holding
address of another variable is said to be a
pointer variable.

Using pointer variable it is easier for


accessing memory location of another
variable.

3
Pointers - Declaration
Syntax:

Data Type * variable;

Where
data type  Type of variable whose address is
to be stored in pointer variable.
*  Value at address operator or pointer
operator.

4
Pointers
int a=1;
int *b; // b is a pointer variable

a b
1 1000

1000 – 1003 2000 – 2003

b = &a; &a = 1000 ; b=1000


b is pointing to address location 1000
*b = * (1000) = 1

Using pointers its possible to access value of another variable


by storing its address.
5
#include<stdio.h>
int main()
{
int arr[5] = {100, 200, 300, 400, 500}, i;
int *ptr = arr;
//Address ptr+i
//Value stored at the address *(ptr+i)
for(i = 0; i < 5; i++)
printf("&arr[%d] = %p\t arr[%d] = %d\n",i,ptr+i,i,*(ptr+i));

ptr=arr;
for(i = 0; i < 5; i++)
{
printf("arr[%d] = %d\n",i,*ptr);
ptr++;
}}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int size;
printf("Enter size of elements:");
scanf("%d", &size);
ptr = (int*)malloc(size * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n"); }
else {
printf("Memory successfully allocated using malloc“);
for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}
printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
} } }
#include <stdio.h>
// student structure
struct student {
char id[15];
char firstname[64];
char lastname[64];
float points;
};

int main(void) {

// student structure variable


struct student std[3];

// student structure pointer variable


struct student *ptr = NULL;

// other variables
int i;

// assign std to ptr


ptr = std;
// get detail for user
for (i = 0; i < 3; i++) {
printf("Enter detail of student #%d\n", (i + 1));
printf("Enter ID: ");
scanf("%s", ptr->id);
printf("Enter first name: ");
scanf("%s", ptr->firstname);
printf("Enter last name: ");
scanf("%s", ptr->lastname);
printf("Enter Points: ");
scanf("%f", &ptr->points);

// update pointer to point at next element


// of the array std
ptr++;
}

// reset pointer back to the starting


// address of std array
ptr = std;
for (i = 0; i < 3; i++) {
printf("\nDetail of student #%d\n", (i + 1));

// display result via std variable


printf("\nResult via std\n");
printf("ID: %s\n", std[i].id);
printf("First Name: %s\n", std[i].firstname);
printf("Last Name: %s\n", std[i].lastname);
printf("Points: %f\n", std[i].points);

// display result via ptr variable


printf("\nResult via ptr\n");
printf("ID: %s\n", ptr->id);
printf("First Name: %s\n", ptr->firstname);
printf("Last Name: %s\n", ptr->lastname);
printf("Points: %f\n", ptr->points);

// update pointer to point at next element


// of the array std
ptr++;
}

return 0;
}
Pointers
To access the value stored in the address we use the unary operator (*) that returns the
value of the variable located at the address specified by its operand.
// C program to demonstrate use of * for pointers in C
#include <stdio.h>
int main()
{
int Var = 10;
int *ptr = &Var;
printf("Value of Var = %d\n", *ptr);
printf("Address of Var = %p\n", ptr);
*ptr = 20; // Value at address is now 20
printf("After doing *ptr = 20, *ptr is %d\n", *ptr);
printf(“Value of Var = %d”, Var);
return 0;
}

11
Pointers
To access the value stored in the address we use the unary operator (*) that returns the
value of the variable located at the address specified by its operand.
// C program to demonstrate use of * for pointers in C
#include <stdio.h>
int main()
{
int Var = 10; Output :
Value of Var = 10
int *ptr = &Var; Address of Var = 0x7fffa057dd4
printf("Value of Var = %d\n", *ptr); After doing *ptr = 20, *ptr is 20

printf("Address of Var = %p\n", ptr);


*ptr = 20; // Value at address is now 20
printf("After doing *ptr = 20, *ptr is %d\n", *ptr);
printf(“Value of Var = %d”, Var);
return 0;
}

12
Pointer Expressions and Pointer Arithmetic

A limited set of arithmetic operations can be performed on pointers. A pointer


may be:

•incremented ( ++ )

•decremented ( — )

•an integer may be added to a pointer ( + or += )

•an integer may be subtracted from a pointer ( – or -= )

(Note: Pointer arithmetic is meaningless unless performed on an array.)


// C program to illustrate Pointer Arithmetic
#include <stdio.h>
int main()
{
int v[3] = {10, 100, 200};
int *ptr;
ptr = v;
for (int i = 0; i < 3; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);
printf("Value of V = %p\n\n", v[i]);
ptr++;
}
}
// C program to illustrate Pointer Arithmetic
#include <stdio.h>
int main()
{ Output:Value of *ptr = 10
Value of ptr = 0x7ffcae30c710
int v[3] = {10, 100, 200}; Value of *ptr = 100
int *ptr; Value of ptr = 0x7ffcae30c714
Value of *ptr = 200
ptr = v;
Value of ptr = 0x7ffcae30c718
for (int i = 0; i < 3; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);
printf("Value of V = %p\n\n", v[i]);
ptr++;
}
}
Behavior of sizeof operator
// 1st program to show that array and pointers are different
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr = arr;
printf("Size of arr[] %d\n", sizeof(arr));

printf("Size of ptr %d", sizeof(ptr));


return 0;
}
Behavior of sizeof operator
// 1st program to show that array and pointers are different
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr = arr;
printf("Size of arr[] %d\n", sizeof(arr));

printf("Size of ptr %d", sizeof(ptr));


return 0;
}

Output:
Size of arr[] 24
Size of ptr 4
Array members are accessed using pointer
arithmetic.
Compiler uses pointer arithmetic to access array element. For example, an
expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the
expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work
for pointer ptr.

#include <stdio.h>
int main()
{ int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr = arr;
printf("arr[2] = %d\n", arr[2]);
printf("*(arr + 2) = %d\n", *(arr + 2));
printf("ptr[2] = %d\n", ptr[2]);
printf("*(ptr + 2) = %d\n", *(ptr + 2));
return 0;
}
Array members are accessed using pointer
arithmetic.
Compiler uses pointer arithmetic to access array element. For example, an
expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the
expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work
for pointer ptr.

#include <stdio.h>
int main() Output:
{ int arr[] = {10, 20, 30, 40, 50, 60};
arr[2] = 30
int *ptr = arr;
*(arr + 2) = 30
printf("arr[2] = %d\n", arr[2]);
printf("*(arr + 2) = %d\n", *(arr + 2)); ptr[2] = 30
printf("ptr[2] = %d\n", ptr[2]); *(ptr + 2) = 30
printf("*(ptr + 2) = %d\n", *(ptr + 2));
return 0;
}
Array parameters are always passed as pointers, even when we
use square brackets.
int fun(int ptr[])
{
int x = 10;
// size of a pointer is printed
printf("sizeof(ptr) = %d\n", sizeof(ptr));
// This is allowed because ptr is a pointer, not array
ptr = &x; Output:
printf("*ptr = %d ", *ptr);
sizeof(ptr) = 4
return 0; *ptr = 10
}

int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
fun(arr);
return 0;
}
Function Pointer in C
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a) In C, like normal data pointers (int *, char
{ *, etc), we can have pointers to
printf("Value of a is %d\n", a); functions. Following is a simple example
} that shows declaration and function call
int main() using function pointer.
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;

/* The above line is equivalent of following two


void (*fun_ptr)(int);
fun_ptr = &fun; Output:
*/
Value of a is 10
// Invoking fun() using fun_ptr
(*fun_ptr)(10);

return 0;
}
Function Pointer as switch case in C

 Like normal pointers, we can have an array of function pointers.


Below example in point 5 shows syntax for array of pointers.

Function pointer can be used in place of switch case. For example,
in below program, user is asked for a choice between 0 and 2 to
do different tasks.

Enter Choice: 0 for add, 1 for subtract and 2 for multiply 2


Multiplication is 150
Function Pointer as switch case in C

#include <stdio.h>
void add(int a, int b) int main()
{
printf("Addition is %d\n", a+b); {
} // fun_ptr_arr is an array of function pointers
void subtract(int a, int b)
{ void (*fun_ptr_arr[])(int, int) = {add, subtract,
printf("Subtraction is %d\n", a-b); multiply};
}
void multiply(int a, int b) unsigned int ch, a = 15, b = 10;
{
printf("Multiplication is %d\n", a*b); printf("Enter Choice: 0 for add, 1 for subtract
} and 2 for multiply\n");
scanf("%d", &ch);
if (ch > 2) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
Question 1
Predict the output of below program.

int main()
{
char arr[] = “VIT Chennai";
printf("%d", sizeof(arr));
return 0;
}
Output

Output: 12

The string “VIT Chennai” has 11 characters, but the


size is 12 because compiler includes a single ‘\0’ (string
terminator) when char array size is not explicitly
mentioned.
Question 2

Predict the output of below program.


int main()
{
int x, y = 5, z = 5;
x = y==z;
printf("%d", x);
return 0;
}
Output

Output: 1

The crux of the question lies in the statement x =


y==z. The operator == is executed before = because
precedence of comparison operators (<=, >= and ==) is
higher than assignment operator =.
The result of a comparison operator is either 0 or 1
based on the comparison result. Since y is equal to z,
value of the expression y == z becomes 1 and the value
is assigned to x via the assignment operator.
Question 3

Predict the output of below program.

int main()
{
printf(" \"GEEKS %% FOR %% GEEKS\"");
getchar();
return 0;
}
Output

Output: “GEEKS % FOR % GEEKS”

Backslash (\) works as escape character for double


quote (“).
Question 4
Predict the output of below program.

int fun(char *str1)


{
char *str2 = str1;
while(*++str1);
return (str1-str2);
}

int main()
{
char *str = "geeksforgeeks";
printf("%d", fun(str));
getchar();
return 0;
}
Output

Output: 13

Inside fun(), pointer str2 is initialized as str1 and str1 is


moved till ‘\0’ is reached (note ; after while loop). So
str1 will be incremented by 13 (assuming that char
takes 1 byte).
Question 5
Predict the output of below program. (Call by
Value)
void fun(int *p)
{
static int q = 10;
p = &q;
}

int main()
{
int r = 20;
int *p = &r;
fun(p);
printf("%d", *p);
getchar();
return 0;
Output

Output: 20

Inside fun(), q is a copy of the pointer p. So if we


change q to point something else then p remains
unaffected.
Question 6
Predict the output of below program(Call by
reference)
void fun(int **p)
{
static int q = 10;
*p = &q;
}

int main()
{
int r = 20;
int *p = &r;
fun(&p);
printf("%d", *p);
getchar();
return 0;
Output
Output 10
Note that we are passing address of p to fun(). p in fun() is actually
a pointer to p in main() and we are changing value at p in fun(). So
p of main is changed to point q of fun(). To understand it better, let
us rename p in fun() to p_ref or ptr_to_p
void fun(int **ptr_to_p)
{
static int q = 10;
*ptr_to_p = &q; /*Now p of main is pointing to q*/
}
Also, note that the program won’t cause any problem because q is
a static variable. Static variables exist in memory even after
functions return. For an auto variable, we might have seen some
weird output because auto variable may not exist in memory after
functions return.
Question 7
Predict the output of below program

int main()
{
int f = 0, g = 1;
int i;
for(i = 0; i < 15; i++)
{
printf("%d \n", f);
f = f + g;
g = f - g;
}
getchar();
return 0;
}
Output
Answer: The function prints first 15 Fibonacci Numbers.
Question 8
Predict the output of below program.

#include<stdio.h>
int main(void)
{
int a = 1;
int b = 0;
b = ++a + ++a;
printf("%d %d",a,b);
getchar();
return 0;
}
Output
Output : 3 6
Question 9
Predict the output of below program.

#include <stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
printf("%p\t%p", p, a);
}
Output

Output:
Same address is printed
Question 10
Predict the output of below program.

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


void main() void main()
{ {
int a[3] = {1, 2, 3}; char *s = "hello";
int *p = a; char *p = s;
printf("%p\t%p", p, a); printf("%p\t%p", p, s);
} }
Output

Output:
Same address is printed
Question 11
Predict the output of below program.

int main()
{
int ary[4] = {1, 2, 3, 4};
printf("\n%ld",ary);
printf("\n%ld",ary+3);
int *p = ary + 3;
printf("\n%d\n", p[-2]);
getch();
}
Output

Output:
Base address of ary
Address of element 4
2
Question 12
Predict the output of below
program(Recursion).

void main()

{
m();
void m()
{
printf("hi");
}
}
Output

Output:
Compile Time error
Question 13
Predict the output of below program.

void main()

{
m();
void m()
{
printf("hi");
}
}
Output

Output:
Compile Time error
Question 14
Predict the output of below program.

#include <stdio.h>
void main()
{
m();
}
void m()
{
printf("hi");
m();
}
Output

Output:
Infinite hi
Question 15
Predict the output of below program.

#include <stdio.h>
void main()
{
static int x = 3;
x++;
if (x <= 5)
{
printf("hi");
main();
}
}
Output

Output:
hi hi
Question 16
Predict the output of below program.

#include <stdio.h>
int main()
{
int ary[4] = {1, 2, 3, 4};
int p[4];
p = ary;
printf("%d\n", p[1]);
}
Output

Output:
Compile Time error
Question 17
Predict the output of below program.

#include <stdio.h>
struct p
{
int k;
char c;
float f;
};
int main()
{
struct p x = {.c = 97, .f = 3, .k = 1};
printf("%f\n", x.f);
}
Output

Output:
3.00000
Question 18
Predict the output of below program.

#include <stdio.h>
struct temp
{
int a;
int b;
int c;
} p[] = {0};
main()
{
printf("%d", sizeof(p));
}
Output

Output:
12
Question 19
Predict the output of below program.

#include <stdio.h>
struct student
{
char *name;
};
struct student s[2];
void main()
{
s[0].name = "alan";
s[1] = s[0];
printf("%s%s", s[0].name, s[1].name);
s[1].name = "turing";
printf("%s%s", s[0].name, s[1].name);
}
Output

Output:
alan alan alan turing
Question 20
Predict the output of below program.
#include <stdio.h>
struct student
{
char *name;
};
struct student s[2], r[2];
void main()
{
s[0].name = "alan";
s[1] = s[0];
r = s;
printf("%s%s", r[0].name, r[1].name);
}
Output

Output:
Compile Time error
Question 21
Predict the output of below program.

#include <stdio.h>
struct student
{
};
void main()
{
struct student s[2];
printf("%d", sizeof(s));
}
Output

Output:
0
Question 22
Predict the output of below program.

#include <stdio.h>
int main(){
static char a;
static long b;
int c;
printf("%d,%d,%d",a,b,c);
return 0;
}
Output

Output:
0 0 Garbage value
Question 23
Predict the output of below program.

int main()
{
int i;
for (i = 0; i<5; i++)
{
int i;
i = 10;
printf("%d ", i) ;
}
return 0;
}
Output

Output:
10 10 10 10 10
Question 23
Predict the output of below program.

#include <stdio.h>
#include <string.h>

int main()
{
printf("GEEKS size = %d \n\n", sizeof("GEEKS"));
printf("GEEKS length = %d \n", strlen("GEEKS"));
return 0;
}
Output

Output:
GEEKS size = 6
GEEKS length = 5

sizeof() function returns the size of the string including


null character while strlen() function returns length of the
string excluding null character.
Question 24
Predict the output of below program.

#include <stdio.h>

int extern i;

int main()
{
printf("%d", i);
}

int i = 10;
Output

Output:
10

With the help of extern keyword, the declaration of


variable can be done any where in the program. Here, i is
a variable which is being declared after the printf
statement outside the main. Still, it can be accessed by
the printf statement as it is an extern variable. For more
details on the keyword extern
Question 25
Predict the output of below program.
#include <stdio.h>
Void main()
{
int a = 10, b = 20, c = 30;
if (c > b > a)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
}
Output

Output:
False
Question 26
Predict the output of below program.
#include <stdio.h>
int main()
{
enum channel {star, sony, zee};

int i = 0;
for(i = star; i <= zee; i++)
{
printf("%d ", i);
}

return 0;
}
Output

Output:
012
Question 27
Predict the output of below program.
#include<stdio.h>
int main()
{
int i, j;
int p = 0, q = 2;

for(i = 0, j = 0; i < p, j < q; i++, j++)


{
printf("GeeksforGeeks\n");
}

return 0;
}
Output

Output:
GeeksforGeeks
GeeksforGeeks
Question 28
Predict the output of below program.
#include <stdio.h>
#define R 4
#define C 4
int main()
{
int mat[R][C] = { {1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12},{13, 14, 15, 16}};
int i,j;
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
printf("%3d ", mat[i][j]);
printf("\n");
}
Output

Output:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Question 29
Predict the output of below program.
int main()
{
int i, j;
int arr[4][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
printf("%d ", j[i[arr]] );
printf("\n");
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
printf("%d ", i[j[arr]] );
}
Output

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
Question 30
Predict the output of below program.
int main()
{
int i, j;
int arr[4][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
printf("%d ", j[i[arr]] );
printf("\n");
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
printf("%d ", i[j[arr]] );
}
Output

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16
Question 31
Predict the output of below program.

int main()
{
int i = 10;

static int x = i;

if (x==i)
printf("x and i are Equal\n");

return 0;
}
Output

Output:
Here, it would seem that, as ‘x’ and ‘i’ are equal, so the
output will be “x and i are Equal”. But the output is quite
unexpected.
As, static variables are load time entity while auto
variables are run time entity an We can not initialize any
load time variable by the run time variable. So,the output
the c code above will show “Compile error”.
Question 32
Predict the output of below program.

int main()
{
int a = 10;
printf("%o %x", a, a);
return 0;
}
Output

Output:
As, %o is used to print the number in octal number
format and %x is used to print the number in hexadecimal
number format. And if we convert decimal 10 to octal ,
we get 12 and in hexadecimal it will give a
Question 33
Predict the output of below program.

int main()
{
int a = 10;
printf("%o %x", a, a);
return 0;
}
Output

Output:
As, %o is used to print the number in octal number
format and %x is used to print the number in hexadecimal
number format. And if we convert decimal 10 to octal ,
we get 12 and in hexadecimal it will give a
Question 34
Predict the output of below program.
int fun()
{
static int num = 40;
return num--;
}

int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
Output

Output:
38 35 32 29 26 23 20 17 14 11 8 5 2

Since num is static in fun(), the old value of num is


preserved for subsequent functions calls. Also, since the
statement return num– is postfix, it returns the old value
of num, and updates the value for next function call.
Question 35
Predict the output of below program.
int main()
{
char *s[] = { "knowledge","is","power"};
char **p;
p = s;
printf("%s ", ++*p);
printf("%s ", *p++);
printf("%s ", ++*p);

getchar();
return 0;
}
Output
Output:
nowledge nowledge s

Let us consider the expression ++*p in first printf(). Since


precedence of prefix ++ and * is same, associativity comes into
picture. *p is evaluated first because both prefix ++ and * are right
to left associative. When we increment *p by 1, it starts pointing to
second character of “knowledge”. Therefore, the first printf
statement prints “nowledge”.
Let us consider the expression *p++ in second printf() . Since
precedence of postfix ++ is higher than *, p++ is evaluated first.
And since it’s a psotfix ++, old value of p is used in this expression.
Therefore, second printf statement prints “nowledge”.
In third printf statement, the new value of p (updated by second
printf) is used, and third printf() prints “s”.
Question 36
Predict the output of below program.

#include<stdio.h>

#define R 10
#define C 20

int main()
{
int (*p)[R][C];
printf("%d", sizeof(*p));
getchar();
return 0;
}
Output
Output:
10*20*sizeof(int) which is “800” for compilers with
integer size as 4 bytes.

The pointer p is de-referenced, hence it yields type of the


object. In the present case, it is an array of array of
integers. So, it prints R*C*sizeof(int).
Question 37
Predict the output of below program.

int main()
{
char arr[] = {1, 2, 3};
char *p = arr;
if(&p == &arr)
printf("Same");
else
printf("Not same");
getchar();
}
Output
Output:
Not Same

&arr is an alias for &arr[0] and returns the address of the


first element in array, but &p returns the address of
pointer p.

You might also like