0% found this document useful (0 votes)
9 views

pointer 2

The document explains the size of pointer variables in C, which is consistent across data types and varies with processor architecture. It discusses the relationship between pointers and arrays, demonstrating how pointers can be used to access and manipulate array elements efficiently. Additionally, it covers the concepts of passing arguments to functions by value and by reference, illustrating the differences with code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

pointer 2

The document explains the size of pointer variables in C, which is consistent across data types and varies with processor architecture. It discusses the relationship between pointers and arrays, demonstrating how pointers can be used to access and manipulate array elements efficiently. Additionally, it covers the concepts of passing arguments to functions by value and by reference, illustrating the differences with code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Size of pointer:

Pointer variable size is not dependent on data type as pointer always stores the address
of other variable which is always integer data type. So, any pointer (int, char, double,
etc.) size will be 2 for 16 bit processor, 4 for 32 bit processor and 8 for 64 bit processor.
sizeof() operator can be used to evaluate size of a variable/pointer in C.

/* program to print size of different types of pointer variables.*/

#include <stdio.h>

int main()

printf("\nsize of char pointer: %d" ,sizeof(char*));

printf("\nsize of int pointer: %d" ,sizeof(int*));

printf("\nsize of float pointer: %d" ,sizeof(float*));

printf("\nsize of long int pointer: %d" ,sizeof(long int*));

printf("\nsize of double pointer: %d\n" ,sizeof(double*));

return 0;

Output

size of char pointer: 4

size of int pointer: 4

size of float pointer: 4

size of long int pointer: 4

size of double pointer: 4


Pointers and Arrays

Any operation that can be done using array subscripts can also be done using pointer in
a faster and efficient way.

Relationship between Arrays and Pointers:

An array is a block of sequential data. Let's write a program to print addresses of array
elements.

#include <stdio.h>

int main() {

int x[5];

int I;

for(i = 0; i < 4; ++i) {

printf("&x[%d] = %p\n", i, &x[i]);

printf("Address of array x: %p", x);

return 0;

Output:
&x[0] = 1450734448

&x[1] = 1450734452

&x[2] = 1450734456

&x[3] = 1450734460

Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x. It is


because the size of int is 4 bytes

Notice that, the address of &x[0] and x is the same. It's because the variable
name x points to the first element of the array.
From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent
to *x.

Similarly,

&x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).

&x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).

...

Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

Example 1: Use of pointer to access the elements of array and add them

#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);

// Equivalent to sum += x[i]

sum += *(x+i);

printf("Sum = %d", sum);

return 0;

Output
Enter 6 numbers: 2

12

Sum = 29

Example 2:

#include <stdio.h>

int main( )

/*Pointer variable*/

int *p;

/*Array declaration*/

int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;

/* Assigning the address of val[0] the pointer

* You can also write like this: * p = var;

* because array name represents the address of the first element */

p = &val[0];

for ( int i = 0 ; i<7 ; i++ )

printf("val[%d]: value is %d and address is %p\n", i, *p, p);

/* Incrementing the pointer so that it points to next element on every increment. */

p++;

}
return 0;

Output:

val[0]: value is 11 and address is 0x7fff51472c30

val[1]: value is 22 and address is 0x7fff51472c34

val[2]: value is 33 and address is 0x7fff51472c38

val[3]: value is 44 and address is 0x7fff51472c3c

val[4]: value is 55 and address is 0x7fff51472c40

val[5]: value is 66 and address is 0x7fff51472c44

val[6]: value is 77 and address is 0x7fff51472c48

Example 3:

#include <stdio.h>

int main( )

int arr[5]={5,10,15,20,25};

int I,*p;

p=arr;

for(i=0;I<5;i++)

printf(“ address of arr[%d]= %u %u %u %u \n”, I, &arr[i], arr+i ,p+I, &p[i]);

printf(“ address of arr[%d]= %d %d %d %d \n”, I, arr[i], *(arr+i) , *(p+I), p[i]);

Output:

Address of arr[0]= 2000 2000 2000 2000

Value of arr[0]= 5 5 5 5
Address of arr[1]= 2002 2002 2002 2002

Value of arr[1]= 10 10 10 10

Address of arr[2]= 2004 2004 2004 2004

Value of arr[2]= 15 15 15 15

Address of arr[3]= 2006 2006 2006 2006

Value of arr[3]= 20 20 20 20

Address of arr[4]= 2008 2008 2008 2008

Value of arr[4]= 25 25 25 25

Points to Note:

1. While using pointers with array, the data type of the pointer must match with the
data type of the array.

2. You can also use array name to initialize the pointer like this: p = val; because
the array name alone is equivalent to the base address of the array.val==&val[0];

3. In the loop the increment operation (p++) is performed on the pointer variable to
get the next location (next element’s location), this arithmetic is same for all types
of arrays (for all data types double, char, int etc.) even though the bytes
consumed by each data type is different.

4. An array name is an internal pointer. The difference between name of an array


and a pointer variable is that name of an array is a constant pointer hence it
always points to the 0th element of the array. As it is not a variable, we can’t
assign some other address to it and also can’t move it by incrementing or
decrementing . In pointer, as it is a variable we can assign any address to it and
also can move it by incrementing or decrementing.

Pointer to Array:
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements.
Example:
#include <stdio.h>
int main()

int i;

int a[5] = {1, 2, 3, 4, 5};

int *p = a; // same as int*p = &a[0]

for (i = 0; i < 5; i++)

printf("%d", *p);

p++;

return 0;

In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address ( a in above case) to act as a pointer and print
all the values.

Replacing the printf(“%d”, *p); statement of above example, with below mentioned
statements will produce following result:
 printf(“%d”, a[i]); : prints the array, by incrementing index;
 printf(“%d”, i[a]); : this will also print elements of array;
 printf(“%d”, a+i); : this will print address of all the array elements;
 printf(“%d”, *(a+i)); : will print value of array element;
 printf(“%d”, *a); : will print value of a[0] only;
 a++ : Compile time error, we cannot change base address of
the array.

The generalized form for using pointer with an array, *(a+i) is same as a[i].
We can also declare a pointer that can point to the whole array instead of only one
element of array.

Example: int (*ptr)[10];

Here ptr is a pointer that can point to an array of 10 integers.

Note: It is necessary to enclose pointer name inside parenthesis. The pointer that
points to the 0th element of array and the pointer that points to whole array are totally
different.

Example:

#include <stdio.h>

main( )

int *p; /* can point to an integer*/

int (*ptr)[5]; /* can point to an array of 5 integers */

int arr[5];

p=arr; /* points to 0th element of arr */

ptr=arr; /* points to whole array arr */

printf(“p = %u, ptr = %u\n”,p,ptr);

p++;

ptr++;

printf(“p = %u, ptr = %u\n”,p,ptr);

Output:

p=3000, ptr=3000

p=3002, ptr=3010
p

3000
2500
3 5 6 7 9
ptr
3000 3002 3004 3006 3008
3000
4500

Here the base type of p is ‘int’ while the base type of ptr is ‘an array of 5 integers’. So if
we write ptr++ then pointer ptr will be shifted forward by 10 bytes.

On dereferencing a pointer we get a value pointed to by that pointer expression and on


dereferencing a pointer to an array, we get the base address of the array to which it
points.

If we find the size of p and ptr in above program then sizeof(p)=2 ,also sizeof(*p)=2 as it
is an integer pointer i.e points to int data. sizeof(ptr) =2 as ptr holds the base address of
array and sizeof(*ptr)=10 as *ptr holds 10 bytes i.e total array.

Array of pointers:

We can declare an array that contains pointers as its elements. Every element of this
array is a pointer variable that can hold address of any variable of appropriate type.

Syntax:

datatype *arrayname[size];

Example: int *arrp[10];

Example:

#include <stdio.h>

main( )

int *pa[3];

int I, a=5,b=10,c=15;

pa[0]=&a;

pa[1]=&b;
pa[0]=&c;

for(i=0;i<3;i++)

printf(“pa[%d] = %u\t”,I,pa[i]);

printf(“ *pa[%d] = %u\n”,I, *pa[i]);

Output:

pa[0]=2012 *pa[0]=5

pa[1]=2560 *pa[1]=10

pa[2]=3020 *pa[2]=15

Here pa is declared as an array of pointers. Every element of this array is a pointer to an


integer.

a b c

5 10 15

2012 2560 3020

pa[0] pa[1] pa[2]

2012 2560 3020


5000 5002 5004

The array of pointers can also contain address of elements of another array.

Example:

#include <stdio.h>

main( )

{
int I, arr[4]={5,10,15,20};

int *pa[4];

for(i=0;i<4;i++)

pa[i]= &arr[i];

for(i=0;i<4;i++)

printf(“pa[%d] = %u\t”,I,pa[i]);

printf(“ *pa[%d] = %d\n”,I, *pa[i]);

Output:

pa[0]=1000 *pa[0]=5

pa[1]=1002 *pa[1]=10

pa[2]=1004 *pa[2]=15

pa[3]=1006 *pa[3]=20

arr[0] arr[1] arr[2] arr[3]


5 10 15 20
1000 1002 1004 1006

pa[0] pa[1] pa[2] pa[3]


1000 1002 1004 1006
2500 2502 2504 2506

Pointers and Functions:

The arguments to the functions can be passed in two ways-


i) Call by value
ii) Call by reference

CALL BY VALUE CALL BY REFERENCE

While calling a function, we pass values of While calling a function, instead of passing
variables to it. Such functions are known the values of variables, we pass address
as “Call By Values”. of variables (location of variables) to the
function known as “Call By References.
In this method, the value of each variable In this method, the address of actual
in calling function is copied into variables in the calling function are copied
corresponding dummy variables of the into the dummy variables of the called
called function. function.
With this method, the changes made to the With this method, using addresses we
dummy variables in the called function would have an access to the actual
have no effect on the values of actual variables and hence we would be able to
variables in the calling function. manipulate them.
// program to illustrate // program to illustrate
// call by value // Call by Reference
#include <stdio.h> #include <stdio.h>
// Function Prototype // Function Prototype
void swapx(int x, int y); void swapx(int*, int*);
// Main function // Main function
int main() int main()
{ {
int a = 10, b = 20; int a = 10, b = 20;
// Pass by Values // Pass reference
swapx(a, b); swapx(&a, &b);
printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);
return 0; return 0;
} }
// Swap functions that swaps // Function to swap two variables
// two values // by references
void swapx(int x, int y) void swapx(int* x, int* y)
{ {
int t; int t;
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);
} }
Output: Output:
x=20 y=10 x=20 y=10
a=10 b=20 a=20 b=10
Thus actual values of a and b remain Thus actual values of a and b get changed
unchanged even after exchanging the after exchanging values of x and y.
values of x and y.
In call by values we cannot alter the values In call by reference we can alter the values
of actual variables through function calls. of variables through function calls.
Values of variables are passes by Simple Pointer variables are necessary to define
technique. to store the address values of variables.

Call by value:

Example-

#include <stdio.h>

value( int x, int y);

main( )

int a=5,b=8;

printf(“ before calling the function, a and b are %d, %d\n”,a,b);

value(a,b);

printf(“ after calling the function, a and b are %d, %d\n”,a,b);

value( int x, int y)

x++;

y++;

printf(“ in function changes are %d,%d\n”,x,y);

Output:

before calling the function, a and b are 5,8

in function changes are 6,9

after calling the function, a and b are 5,8


Before Execution of Function After incrementing x and y

main() value() main() value()

a 5 x 5 a 5 x 6

2000 2012 2000 2012

b 8 y 8 b 8 y 9

2002 2014 2002 2014

Call by reference:

Example:

#include <stdio.h>

ref( int *, int *);

main( )

int a=5,b=8;

printf(“ before calling the function, a and b are %d, %d\n”,a,b);

ref(&a, &b);

printf(“ after calling the function, a and b are %d, %d\n”,a,b);

ref( int *p, int *q)

(*p)++;

(*q)++;

printf(“ in function changes are %d,%d\n”, *p, *q);

}
Output:

before calling the function, a and b are 5,8

in function changes are 6,9

after calling the function, a and b are 6,9

Before Execution of Function After incrementing *p and *q

main() ref() main() ref()

a 5 p 2000 a 6 p 2000

2000 2012 2000 2012

b 8 b 9 q 2002
q 2002
2002 2002 2014
2014

Returning more than one value from a function:

We have studied that we can return only one value from a function through return
statement. This limitation can be overcome by using call by reference.

Example:

#include<stdio.h>
void return_more_than_one(int a, int b, int *sum, int *diff, int *prod);

int main()
{
int x = 40, y = 10, sum, diff, prod;

return_more_than_one(x, y, &sum, &diff, &prod);

printf("%d + %d = %d\n",x, y, sum);


printf("%d - %d = %d\n",x, y, diff);
printf("%d * %d = %d\n",x, y, prod);
return 0;
}
void return_more_than_one(int a, int b, int *sum, int *diff, int *prod)
{
*sum = a+b;
*diff = a-b;
*prod = a*b;
}

Output:
40 + 10 = 50

40 - 10 = 30

40 * 10 = 400

How it works:

In return more than one() function a and b are passed using call by value, where as
sum, diff and prod are passed using call by reference. As a result return more than
one() function knows the address of sum, diff and prod variables, so it access these
variables indirectly using a pointer and changes their values.

Function returning pointer:

We can have a function that returns a pointer.

Syntax:

type *func(type1,type2,…);

Example: float *fun( int, char); /* it returns a pointer to float */

int *fun( int, int); /* it returns a pointer to int */

While returning a pointer , make sure that the memory address returned by the pointer
will exist even after the termination of function. It is recommended that never return a
pointer that points to a local variable.

Example:

main()

int *ptr;

ptr=func();

…………….
}

int *func()

int x=5;

int *p=&x;

……………..

return p;

Here a pointer is returned which points a local variable. We know that a local variable
exists only inside the function. Suppose the variable x is stored at 3500, so the value
of p will be 3500 and this value returned by function func(). As soon as fun() terminates,
the local variable x will not exist.

The address returned by function () is assigned to ptr inside main(), so now ptr will
contain address 3500, when we dereference ptr, we are trying to access the value of a
variable that no longer exists. so never return a pointer that points to a local variable.

Example to show use of function that returns pointer:

#include<stdio.h>

int *fun(int *p, int*n);

main()

int arr[10]={1,2,3,4,5,6,7,8,9,10}, n, *ptr;

n=5;

ptr= fun(arr,n);

printf(“ value of arr = %u, value of ptr = %u, value of *ptr = %d\n”, arr, ptr, *ptr);

int *fun(int *p, int*n)

p=p+n;
return p;

Output:

value of arr = 65104 , value of ptr = 65114 , value of *ptr = 6

Pointer to function:

Every function has an address like variables in the program.

Syntax of declaration of a Pointer to function:

return type ( *ptr_name) (type1, type2, ….. );

Example:

float ( *fp) (int);

Here fp is a pointer that can point to any function that returns a float value and accepts
an int value as argument.

char (*func_p)(float,char);

Here func_p is a pointer that can point to functions returning char value and accepting
float and char value as arguments.

This declaration is somewhat same as declaration of a function, except that the pointer
name is preceded by a * and is enclosed in parenthesis.

The next step is to assign a function’s address to a pointer to function.

float ( *fp) (int , int); /* Declaring a function pointer */

float func (int, int); /* Declaring a function */

fp= func; /* Assign address of function func() to pointer fp */

Declaring a function is necessary before using its address anywhere in the program
because without declaration the compiler will not know about this function and will
generate error.

Calling a function through function pointer:

r = (*fp) (a,b); /* calling a function via function pointer */

The result of calling a function by it’s name or by function pointer is exactly the same.
#include<stdio.h>
main()

float (*fp)(int, float);

float add (int, float),result;

fp=add; /* Assign address of function add() to pointer fp */

/* invoking a function directly using function’s name */

result = (*fp)(5, 6.6);

printf(“%f \n”, result);

/* invoking a function indirectly by dereferencing function pointer */

result = (*fp) (5, 6.6);

printf(“%f \n”, result);

float add (int a , float b)

return(a+b);

Output:

11.600000

11.600000

You might also like