Pointers 1
Pointers 1
Memory
The formatting functions are available as a part
of the standard library. The following functions
are used to format data in memory:
sprintf()
sscanf()
where:
string is a pointer to the destination string in memory,
which will contain the formatted data as per the
format-specification.
sprintf(str, “%02d-%02d-%02d”,28,8,89);
printf(“The day is %d, suffix is: %s, month is: %s, year is:
%%d\n”, day, suffix, mnth, year);
Practice 5.7
What data is assigned to the variable string by each of
the following?
sprintf (string, "%04d%3.2f%2s", 21, 4.576, "Hi");
sprintf (string, "%10s", "ABC");
sscanf ("0987APZ", "%4d%s", &num, string);
a. “00214.58Hi”
b. “ABC”
c. “APZ”
Pointer in c
A pointer is a variable like any other variable
which contain an address of another variable,
having same data types as pointer type.
type *pointer-name;
#include <stdio.h>
int main () {
return 0;
}
Void Pointer
The void pointer in C is a pointer that is not
associated with any data types. It points to
some data location in the storage. This means
that it points to the address of variables. It is
also called the general purpose pointer.
#include <stdio.h>
int main()
{
int a = 10;
void *ptr = &a; // Void pointer
printf("Value of a: %d\n", *(int*)ptr);
// Typecasting is needed
return 0;
}
Advantages of Void Pointers
Following are the advantages of void pointers
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
*ptr = 42;
free(ptr); // Memory deallocated
// Accessing `ptr` now creates a dangling pointer issue
return 0;
}
Wild Pointer
An uninitialized pointer that can cause unpredictable
behavior.
#include <stdio.h>
int main()
{
int *ptr; // Wild pointer
// Use after initialization to avoid issues
return 0;
}
Function Pointer
A pointer used to store the address of a function.
#include <stdio.h>
void display()
{
printf("Function pointer example.\n");
}
int main()
{
void (*funcPtr)() = display; // Function pointer
funcPtr(); // Call the function
return 0;
}
Pointer to Pointer
Pointer to a pointer is a form of multiple indirection or
a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a
pointer, the first pointer contains the address of the
second pointer, which points to the location that
contains the actual value.
Example :
following is the declaration to declare a pointer to a
pointer of type int −
int **var;
When a target value is indirectly pointed to by a
pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown
below in the example −
Pointer to Pointer
#include <stdio.h>
int main()
{
int a = 10;
int *ptr = &a; // Pointer to int
int **ptr2 = &ptr; // Pointer to pointer
printf("Value of a: %d\n", **ptr2);
return 0;
}
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr,***p3,****p4;
var = 3000;
// take the address of var
ptr = &var;
// take the address of ptr using address of operator &
pptr = &ptr;
p3=&pptr;
p4=&p3;
// take the value using pptr
printf("Value of var :%d\n",var);
printf("Value available at *ptr :%d\n",*ptr);
printf("Value available at **pptr :%d\n",**pptr);
printf("Value available at ***p3 :%d\n",***p3);
printf("Value available at ****p4 :%d\n",****p4);
return 0;
}
#include<stdio.h>
int main()
{
int x[5]={1,2,9,8,5};
int *p;
p=x; //p=&x[0];
printf("%d\t%d\t%d\t%d\t%d\n",p[0],p[1],p[2],p[3],p[4]);
printf("%d\t%d\t%d\t%d\t%d\n",&p[0],&p[1],&p[2],&p[3],
&p[4]);
printf("%d\t%d\n",x[0],p);
printf("%d\t%d\n",*p,p);
printf("%d\t%d\n",*p++,p);
printf("%d\t%d\n",*(++p),p);
printf("%d\t%d\n",*(p+2),p);
p=&x[3];
printf("%d\t%d\n",*p,p);
printf("%d\t%d\n",*(p-2),p);
}
Constant Pointer
A pointer that cannot change the memory location it
points to.
#include <stdio.h>
int main()
{
int a = 10, b = 20;
int *const ptr = &a; // Constant pointer
*ptr = 30; // Allowed: changing the value of 'a'
// ptr = &b; // Error: cannot change the address
return 0;
}
Usage of Pointers
Pointer arithmetic
There are four arithmetic operators that can be used
in pointers: ++, --, +, -
Array of pointers
You can define arrays to hold a number of pointers.
Pointer to pointer
C allows you to have pointer on a pointer and so on.
float *ptr_to_float;
the pointer variable ptr_to_float can point to a
variable of type .
ptr=&x;
y=*ptr;
ptr++;
does not necessarily mean that ptr now points
to the next memory location. What memory
location it will point to will depend upon the
datatype to which the pointer points. Consider
the following example:
#include <stdio.h>
char college[]= “CIMAGE COLLEGE”;
main()
{
char *ptr;
ptr=college;
printf(“%s”, college); /* output: CIMAGE COLLEGE*/
printf(“%s”,ptr); /* output: CIMAGE COLLEGE
*/
ptr++;
printf(“%s”,college); /* output: CIMAGE COLLEGE */
printf(“%s",ptr); /* output: IMAGE COLLEGE*/
ptr++;
printf(“%s”,college); /* output; CIMAGE COLLEGE*/
printf(“%s”,ptr); /* output: MAGE COLLEGE*/
#include <stdio.h>
char str[13]={“CIMAGE PATNA”};
char str1[]={“MAGIC”};
main()
{
char *ptr;
printf(“We are playing around with %s", str);
/* Output: We are playing around with CIMAGE PATNA */
ptr=str ; /* ptr now points to whatever str is pointing to */
printf(“We are playing around with %s" ,ptr);
/* Output: We are playing around with CIMAGE PATNA */
}
Although the preceding example gives the
impression that the two pointers are equal,
there is a very subtle difference between str
and ptr.
Both, ptr and str are pointers to char datatype.
However, str is a pointer, which is static.
ptr=str1;
char *things[6];
printf(“%s”, things[2]);
All's well,
File not found
No read permission for file
Insufficient memory
No write permission for file
Syntax
The syntax for creating a constant using #define in
the C language is:
OR
Note
Do NOT put a semicolon character at the end of
#define statements. This is a common mistake.
Example
Let's look at how to use #define directives with
numbers, strings, and expressions.
Number
The following is an example of how you use the #define
directive to define a numeric constant:
#define AGE 10
In this example, the constant named AGE would contain
the value of 10.
String
You can use the #define directive to define a string
constant.
For example:
For example:
#include <stdio.h>
int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
return 0;
}
# include<stdio.h>
# define ERRORS 5
char *err_msg[]= {
/*Note the missing index*/
“All's well”,
“File not found”,
“No read permission for file”,
“Insufficient memory”,
“No write permission for file”
};
main()
{
int err_no;
for ( err_no = 0; err_no < ERRORS; err_no++ )
{
printf (“\nError message %d is : %s\n”, err_no + 1,
err_msg[err_no]);
}
}
Now, let us complicate things a little further
and apply pointer arithmetic to two-d arrays.
Consider the following declaration:
int num[3][4]=
{
{3, 6, 9, 12},
{15, 25, 30, 35},
{66, 77, 88, 99}
};
Pointer expression Variable Value
*(*num) num[0][0] 3
*(*num+1) num[0][1] 6
*(*(num+1)) num[1][0] 15
*(*(num+1)+ 1) num[1][1] 25
*(*(num+1)+ 1)+1 num[1][1] + 1 26
The following code snippet would help you to understand
the use of the indirection symbol to access various
elements:
int main ()
{
unsigned long sec;
getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}
#include <stdio.h>
void test() {
// test function that does nothing
return ;
}
int main() {
int a = 5;
// printing the address of variable a
printf("Address of variable = %p\n", &a);
Example :
void *(*fp) (int *, int *);
int length = 5;
// Different ways to call the function
// function declaration
int areaRectangle(int, int);
int main() {
int length, breadth, area;
/* function pointer declaration note that our pointer declaration has identical
arguments as the function it will point to
int (*fp)(int, int);
// function definition
int areaRectangle(int l, int b) {
int area_of_rectangle = l * b;
return area_of_rectangle;
}
Example: Array of function pointers
int main() {
int a, b;
float (*operation[4])(int, int);
operation[0] = add;
operation[1] = subtract;
operation[2] = multiply;
operation[3] = divide;
return 0;
}
Syntax of malloc() in C
for(i=0;i<n;i++)
{
ptr[i]=i+1;
}
for(i=0;i<n;i++)
{
printf("%d ",ptr[i]);
}
int k;
printf("\nEnter new size of Dynamic Array........");
scanf("%d",&k);
ptr=(int *)realloc(ptr,k*sizeof(int));
for(i=n;i<k;i++)
{
ptr[i]=i+1;
}
printf("\n");
for(i=0;i<k;i++)
{
printf("%d ",ptr[i]);
}
free(ptr);
}
return 0;
}
C calloc() function
“calloc” or “contiguous allocation” method in C is
used to dynamically allocate the specified
number of blocks of memory of the specified
type. it is very much similar to malloc() but has
two different points and these are:
Syntax of calloc() in C
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
Syntax of free() in C
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main()
{ // This pointer will hold the base address of the
//block created
int *ptr, *ptr1;
int n, i;
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
free(ptr);
}
return 0;
}
Exercises
Exercise 1
Write a program that accepts 2 strings and displays
the position where the second string occurs in the
first. Display 0 if the second string does not occur in
the first.
Exercise 2
Write a function to accept and sort a string in
ascending order of its elements.
Exercise 3
For example:
#include <stdio.h>
#define NAME “CIMAGE "
#define AGE 14
#define MIN(a,b) ((a)<(b)?(a):(b))
int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
printf("Minimum between 10 and 20 is:%d\n",MIN(10,20));
return 0;
}
# include<stdio.h>
# define ERRORS 5
char *err_msg[]= {
/*Note the missing index*/
“All's well”,
“File not found”,
“No read permission for file”,
“Insufficient memory”,
“No write permission for file”
};
main()
{
int err_no;
for ( err_no = 0; err_no < ERRORS; err_no++ )
{
printf (“\nError message %d is : %s\n”, err_no + 1,
err_msg[err_no]);
}
}
Exercises
Exercise 1
Write a program that accepts 2 strings and displays
the position where the second string occurs in the
first. Display 0 if the second string does not occur in
the first.
Exercise 2
Write a function to accept and sort a string in
ascending order of its elements.
Exercise 3
Write programs to do the following:
1.Copy the contents of a string str2 into
str1.
2.Add the contents of a string str2 to the
contents of str1.
where str1 and str2 are arrays of type char.