Pointers Examples: Page 1 of 7
Pointers Examples: Page 1 of 7
int main()
{
int y = 20;
fun(y);
printf("%d", y);
return 0;
}
1Ans:
int main()
{
int y = 20;
fun(&y);
printf("%d", y);
return 0;
}
2Ans:30
3.
#include <stdio.h>
int main()
{
int *ptr;
int x;
ptr = &x;
*ptr = 0;
Page 1 of 7
printf(" x = %dn", x);
printf(" *ptr = %dn", *ptr);
*ptr += 5;
printf(" x = %dn", x);
printf(" *ptr = %dn", *ptr);
(*ptr)++;
printf(" x = %dn", x);
printf(" *ptr = %dn", *ptr);
return 0;
}
3 Ans: x = 0
*ptr = 0
x=5
*ptr = 5
x=6
*ptr = 6
4.Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes
4 bytes.
#include <stdio.h>
int main()
{
int arri[] = {1, 2 ,3};
int *ptri = arri;
return 0;
}
4 Ans: sizeof arri[] = 12 sizeof ptri = 4 sizeof arrc[] = 3 sizeof ptrc = 4
5.Assume that float takes 4 bytes, predict the output of following program.
#include <stdio.h>
int main()
Page 2 of 7
{
float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
float *ptr1 = &arr[0];
float *ptr2 = ptr1 + 3;
return 0;
}
5 Ans: 90.500000 3
6.
int f(int x, int *py, int **ppz)
{
int y, z;
**ppz += 1;
z = **ppz;
*py += 2;
y = *py;
x += 3;
return x + y + z;
}
void main()
{
int c, *b, **a;
c = 4;
b = &c;
a = &b;
printf("%d ", f(c, b, a));
return 0;
}
6 Ans:19
7.
#include<stdio.h>
void f(int *p, int *q)
{
p = q;
*p = 2;
}
int i = 0, j = 1;
Page 3 of 7
int main()
{
f(&i, &j);
printf("%d %d n", i, j);
getchar();
return 0;
}
7 Ans: 0 2
*(*nums) nums[0][0] 16
*(*nums + 1) nums[0][1] 18
*(*nums + 2) nums[0][2] 20
*(*(nums + 1) + 1) nums[1][1] 26
*(*(nums + 1) + 2) nums[1][2] 27
Page 4 of 7
Example 1: Pointers and Arrays
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
return 0;
Page 5 of 7
}
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
num1 = 10
num2 = 5
The address of num1 and num2 are passed to the swap() function using swap(&num1,
&num2); .
Page 6 of 7
Pointers n1 and n2 accept these arguments in the function definition.
#include <stdio.h>
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Page 7 of 7