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

Pointer

The document discusses pointers in C programming. Some key points: - Pointers are variables that store memory addresses. They allow indirect access to values in memory. Pointer variables must be declared before use. - The & operator returns the memory address of a variable. The * operator accesses the value at the memory address a pointer refers to. - Pointer arithmetic allows incrementing, decrementing, adding, and subtracting pointers. - Dynamic memory allocation using malloc, calloc, and realloc allows allocating memory at runtime without knowing the size beforehand.

Uploaded by

sarthakmalik5098
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Pointer

The document discusses pointers in C programming. Some key points: - Pointers are variables that store memory addresses. They allow indirect access to values in memory. Pointer variables must be declared before use. - The & operator returns the memory address of a variable. The * operator accesses the value at the memory address a pointer refers to. - Pointer arithmetic allows incrementing, decrementing, adding, and subtracting pointers. - Dynamic memory allocation using malloc, calloc, and realloc allows allocating memory at runtime without knowing the size beforehand.

Uploaded by

sarthakmalik5098
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Ankur Rastogi Unit-II Pointers

Pointer
• Pointers are variables that contain memory addresses as their values.

• A variable name directly references a value.

• A pointer indirectly references a value. Referencing a value through a pointer is


called indirection.

• A pointer variable must be declared before it can be used.

Declaring Pointers

typename *ptrname;

int marks=75;

int *ip;

ip = &marks;

ip is a pointer. Here we r assigning the address of marks to the ip.

char *ch1, *ch2; /* ch1 and ch2 both are pointers to type char */
float *value, percent; /* value is a pointer to type float, and
/* percent is an ordinary float variable */

Initializing Pointers

pointer = &variable;
p_rate = &rate; /* assign the address of rate to p_rate */

#include <stdio.h>
int var = 1;
int *ptr;
main()
{
/* Initialize ptr to point to var */
ptr = &var;
/* Access var directly and indirectly */
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr);
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
return 0;
}

2013 Page 1
Ankur Rastogi Unit-II Pointers

Output:

Direct access, var = 1


Indirect access, var = 1
The address of var = 4264228
The address of var = 4264228

• & (address operator)

– & -- "address operator" which gives or produces the memory address of a


data variable

– Returns address of operand

int y = 5;

int *yPtr;

yPtr = &y; //yPtr gets address of y

yPtr “points to” y

• * (indirection/dereferencing operator)

– * -- "dereferencing operator" which provides the contents in the memory


location specified by a pointer

– Returns a synonym/alias of what its operand points to

*yptr returns y (because yptr points to y)

– * can be used for assignment

• Returns alias to an object

*yptr = 7; // changes y to 7

– Dereferenced pointer (operand of *) must be an lvalue (no constants)

Pointer Arithmetic

• Arithmetic operations can be performed on pointers

• A pointer may be incremented or decremented

• An integer may be added to or subtracted from a pointer.

• Pointer variables may be subtracted from one another.

2013 Page 2
Ankur Rastogi Unit-II Pointers

• Pointer variables can be used in comparisons, but usually only in a comparison to


NULL.

• When an integer is added to or subtracted from a pointer, the new pointer value is
changed by the integer times the number of bytes in the data variable the pointer is
pointing to.

• For example, if the pointer valptr contains the address of a double precision variable
and that address is 234567870, then the statement:

valptr = valptr + 2; would change valptr to 234567886

example-

void main()

int x=7;

int *ptr;

ptr=&x;

ptr=ptr+1;

printf("Value of x=%d\n",x);

printf("Address of x(&x) %d\n",&x);

printf("Address of x %d\n",ptr);

getch();

• 5 element int array on machine with 4 byte ints

– vPtr points to first element v[0] at location 3000. (vPtr = 3000)

– vPtr +=2; sets vPtr to 3008

• vPtr points to v[2] (incremented by 2), but machine has 4 byte ints.

2013 Page 3
Ankur Rastogi Unit-II Pointers

• Subtracting pointers

– Returns number of elements from one to the other.

vPtr2 = v[2];

vPtr = v[0];

vPtr2 - vPtr == 2.

• Pointer comparison ( <, == , > )

– See which pointer points to the higher numbered array element

– Also, see if a pointer points to 0

Example-

void main()

int x[10],i;

int *ptr;

x[0]=7;

ptr=&x[0];

printf("Value of x=%d\n",x[0]);

printf("Address of x(&x) %d\n",&x);

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

ptr=ptr+1;

*ptr=x[i]+1;

printf("\nAddress of x %d\n",ptr);

2013 Page 4
Ankur Rastogi Unit-II Pointers

printf("Value of x(*ptr)=%d\n",*ptr);

getch();

Dynamic memory allocation


In some programming contexts, you want to process data but don’t know what size of it is.
For example, you read a list of students from file but don’t know how many students record
there. Yes, you can specify the enough maximum size for the array but it is not efficient in
memory management. C provides you a powerful and flexible way to manage memory
allocation at runtime. It is called dynamic memory allocation. Dynamic means you can
specify the size of data at runtime. C programming language provides a set of standard
functions prototype to allow you to handle memory effectively. With dynamic memory
allocation you can allocate and free memory as needed.

Getting to know the size of data


Before allocating memory, we need to know the way to identify the size of each data so we
can allocate memory correctly. We can get the size of data by using sizeof() function. sizeof()
function returns a size_t an unsigned constant integer. For example to get the size of integer
type you can do as follows:

sizeof(int);

It returns 4 bytes in typical 32 bit machines. Here is a simple program which prints out the
size of almost common C data type.

void main()

printf("size of int is %d byte(s)\n",sizeof(int));

printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int));

printf("size of short is %d byte(s)\n",sizeof(short));

printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short));

printf("size of long is %d byte(s)\n",sizeof(long));

printf("size of char is %d byte(s)\n",sizeof(char));

printf("size of float is %d byte(s)\n",sizeof(float));

2013 Page 5
Ankur Rastogi Unit-II Pointers

printf("size of double is %d byte(s)\n",sizeof(double));

getch();

And you can see the output:

size of int is 4 byte(s)


size of unsigned int is 4 byte(s)
size of short is 2 byte(s)
size of unsigned short is 2 byte(s)
size of long is 4 byte(s)
size of char is 1 byte(s)
size of float is 4 byte(s)
size of double is 8 byte(s)

Allocating memory
We use malloc() function to allocate memory. Here is the function interface:

void * malloc(size_t size);

malloc function takes size_t as its argument and returns a void pointer. The void pointer is
used because it can allocate memory for any type. The malloc function will return NULL if
requested memory couldnt be allocated or size argument is equal 0. Here is an example of
using malloc function to allocate memory:

int *ptr;

int size=5;

ptr=(int *)malloc(size *sizeof(int));

sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer
now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the
malloc function allocate memory space is successful or not by checking the return value.

if(pi == NULL)

fprintf(stderr,"error occurred: out of memory");

exit(EXIT_FAILURE);

2013 Page 6
Ankur Rastogi Unit-II Pointers

Lets look the following program:

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main()

int n,i;

printf("Enter the size of array\n");

scanf("%d",&n);

int *a=(int *)malloc(n*sizeof(int));

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

a[i]=i+1;

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

printf("%d\n",a[i]);

free(a);

getch();

Beside malloc function, C also provides two other functions which make convenient ways to
allocate memory:

void *calloc(size_t num, size_t size);

void *realloc(void *ptr, size_t size);


2013 Page 7
Ankur Rastogi Unit-II Pointers

Calloc function not only allocates memory like malloc but also allocates memory for a group
of objects which is specified by num argument.

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main()

int n,i;

printf("Enter the size of array\n");

scanf("%d",&n);

int *a=(int *)calloc(n,sizeof(int));

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

a[i]=i+1;

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

printf("%d\n",a[i]);

free(a);

getch();

Realloc function is used to resize the size of memory block, which is already allocated. It
found use of in two situations :

(i) If the allocated memory block is insufficient for current application.


(ii) If the allocated memory is much more than what is required.

#include<stdio.h>

2013 Page 8
Ankur Rastogi Unit-II Pointers

#include<stdlib.h>

#include<conio.h>

void main()

int n,i;

printf("Enter the size of array\n");

scanf("%d",&n);

int *a=(int *)malloc(n*sizeof(int));

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

a[i]=i+1;

int *b=(int *)realloc(a,2*n*sizeof(int));

for(i=0;i<2*n;i++)

printf("%d\n",b[i]);

free(b);

getch();

Freeing memory
When you use malloc to allocate memory you implicitly get the memory from a dynamic
memory pool which is called heap. The heap is limited so you have to deallocate or free the
memory you requested when you don't use it in any more. C provides free function to free
memory. Here is the function prototype:

void free(void *ptr);

You should always use malloc and free as a pair in your program to a void memory leak

2013 Page 9
Ankur Rastogi Unit-II Pointers

Program to show the use of free() and realloc().

#include<stdio.h>

#include<conio.h>

int main()

char *msg;

msg=(char *)malloc(30 * sizeof(char));

strcpy(msg,"Able Was I");

printf("the message now is %s\n",msg);

msg=(char *)realloc(msg,50);

strcpy(msg,"i m writing the program of realloc function");

printf("\n the message is now %s",msg);

free(msg);

getch();

Pointers and Arrays

• Arrays and pointers closely related

– Array name like a constant pointer

– Pointers can do array subscripting operations

• Declare an array b[5] and a pointer bPtr

bPtr = b;

Array name actually a address of first element

OR

bPtr = &b[0]

Explicitly assign bPtr to address of first element

• Element b[n]

2013 Page 10
Ankur Rastogi Unit-II Pointers

– can be accessed by *( bPtr + n )

– n - offset (pointer/offset notation)

– Array itself can use pointer arithmetic.

b[3] same as *(b + 3)

– Pointers can be subscripted (pointer/subscript notation)

bPtr[3] same as b[3]

• Arrays can contain pointers - array of strings

char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" };

– String: pointer to first character

– char * - each element of suit is a pointer to a char

– Strings not actually in array - only pointers to string in array

• suit array has a fixed size, but strings can be of any size.

Example 1:-

void main()

char *a[4]={"this","is","string","pointer"},i;

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

puts(a[i]);

getch();

2013 Page 11
Ankur Rastogi Unit-II Pointers

Example 2:-

void main()

int *ptr,a[10],i;

a[0]=1;

ptr=&a[0];

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

ptr=ptr+1;

*ptr=a[0]+i;

printf("Address %d\n",ptr);

printf("value %d\n",*ptr);

getch();

Pointers and Functions

• Pointers can be used to pass addresses of variables to called functions, thus allowing
the called function to alter the values stored there.

• We looked earlier at a swap function that did not change the values stored in the
main program because only the values were passed to the function swap.

• This is known as "call by value".

• If instead of passing the values of the variables to the called function, we pass their
addresses, so that the called function can change the values stored in the calling
routine. This is known as "call by reference" since we are referencing the variables.

• The following shows the swap function modified from a "call by value" to a "call by
reference". Note that the values are now actually swapped when the control is
returned to main function.

2013 Page 12
Ankur Rastogi Unit-II Pointers

void swap ( int *a, int *b ) ;

int main ( )

int a = 5, b = 6;

printf("a=%d b=%d\n",a,b) ;

swap (&a, &b) ;

printf("a=%d b=%d\n",a,b) ;

getch() ;

void swap( int *a, int *b )

int temp;

temp= *a; *a= *b; *b = temp ;

printf ("a=%d b=%d\n", *a, *b);

2013 Page 13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy