Pointers

Command Line Arguments

The arguments passed from command line are called command line arguments. These arguments are handled by main() function.
To support command line argument, you need to change the structure of main() function as given below.

int main(int argc, char *argv[] )


argc (ARGument Count) is int and counts the number of arguments. So if we pass a value to a program, value of argc would be 2 (one for file name as the first argument and one for argument)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings.
Argv[0] is the name of the program , After that till argv[1],argv[2],argv[argc-1] every element is command -line arguments.
Let's see the examples of command line arguments
 #include<stdio.h>
void main(int argc, char *argv[])
{
printf("Name of the Program is %s \n",argv[0]);

printf("no of arguments passed %d",argc);
}
   
   
//sample program to print all the arguments passed using loops  
  
#include<stdio.h>
#include<conio.h>
void main(int argc, char *argv[])
{
int i;
clrscr();
printf("Name of the Program is %s \n",argv[0]);

printf("no of arguents passed %d\n",argc);

for(i=0;i<argc;i++)
{
printf("Argument %d is %s\n",i,argv[i]);
}
//c program to Count no of vowels in a Argument using command line arguments

#include<stdio.h>
#include<conio.h>
void main(int argc, char *argv[])
{
int i,count=0;
char *str;
str=argv[1];
for(i=0;i<strlen(str)-1;i++)
{
if(str[i]=='a'||str[i]=='A'||str[i] == 'e' || str[i] == 'E'
  || str[i] == 'i' || str[i] == 'I' || str[i] =='o'
  || str[i]=='O' || str[i] == 'u' || str[i] == 'U')
count++;
}
printf("%d",count);
}
//c program to Count no of vowels in a Argument using functions     
#include<stdio.h>
#include<conio.h>
void main(int argc, char *argv[])
{
int c;
printf("No of arguments are %d",argc);
printf("program name is %s \n",argv[0]);

if(argc>=2)
{
printf("no arguments passed\n %s %s",argv[1],argv[2]);
}
else
printf("first argument is %s \n",argv[1]);

c=vowel(argv[1]);
printf("\n no of vowels in a string is %d",c);

}
int vowel(char *str)
{
int i,count=0;
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='a'||str[i]=='A'||str[i] == 'e' || str[i] == 'E'
  || str[i] == 'i' || str[i] == 'I' || str[i] =='o'
  || str[i]=='O' || str[i] == 'u' || str[i] == 'U')
{
count+=1;
}
}
return count;
}

Null Pointer in C

A Null Pointer is a pointer that does not point to any memory location. If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When a NULL value is assigned to the pointer, then it is considered as a Null pointer.
When we do not assign any memory address to the pointer variable.
     #include<stdio.h>
     #include<conio.h>  
    void main()  
    {  
        int *ptr;  
       printf("Address: %d", ptr);   
       printf("Value: %d", *ptr);   
    }  
    
In the above code, we declare the pointer variable *ptr, but it does not contain the address of any variable. According to the stack memory concept, the local variables of a function are stored in the stack, and if the variable does not contain any value, then it shows the garbage value. The above program shows some unpredictable results.

We can avoid the above situation by using the Null pointer. A null pointer is a pointer pointing to the 0th memory location, which is a reserved memory and cannot be dereferenced.
     #include<stdio.h>
     #include<conio.h>  
    void main()  
    {  
        int *ptr=NULL;  
        if(ptr!=NULL)  
        {  
            printf("value of ptr is : %d",*ptr);  
        }  
        else  
        {  
            printf("Invalid pointer");  
        }  
    }  
    

Dereference pointer: a pointer is a variable that stores the address of another variable. The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.

Void Pointer / Generic pointer

pointer which stores the address of another variable, the address assigned to a pointer should be of the same type as specified in the pointer declaration. For example, int pointer cannot point to the float variable i.e., it can point to only int type variable.
To overcome this problem, we use a pointer to void. A pointer to void means a generic pointer that can point to any data type. We can assign the address of any data type to the void pointer, and a void pointer can be assigned to any type of the pointer without performing any explicit typecasting.
We use void pointers because of its reusability. Void pointers can store the object of any type, and we can retrieve the object of any type by using the indirection operator with proper typecasting.
 //Example 1
     #include<stdio.h>
     #include<conio.h>  
    void main()    
    {  
       int a=10;  
       void *p;  
       p=&a;  
       printf("Value which is pointed by p pointer : %d",*(int*)p);  
         
    }  
   
   //Example 2
      #include<stdio.h>
     #include<conio.h>  
    void main()   
    {   
       float a[4]={6.1,2.3,7.8,9.0};  
       void *ptr;  
       ptr=a;  
       for(int i=0;i<4;i++)  
      {  
          printf("%f,",*((float*)ptr+i));  
       }
     }  
       
      

Dynamic Memory Allocation in C

Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
  1. malloc()- allocates single block of memory
  2. calloc()-allocates multiple block of memory.
  3. realloc()-reallocates the memory occupied by malloc() or calloc().
  4. free()-frees the dynamically allocated memory.

static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time
memory can't be increased while executing program. memory can be increased while executing program.
used in array. used in linked list.
It is faster and has high time efficiency It is slower and has low time efficiency
malloc() has a default garbage value. calloc() is initialized by zero

malloc:


The malloc or memory allocation method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time, so it has garbage value initially. it returns NULL if memory is not sufficient. The syntax of malloc() function is given below:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i, *ptr, sum = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    ptr = (int*) malloc(n * sizeof(int));
    if(ptr == NULL)     // if memory cannot be allocated 
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements: ");
    for(i = 0; i < n; i++)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }
    printf("Sum = %d", sum);
    free(ptr); // deallocating the memory

    return 0;
}
   

Calloc:


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:
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc().
It returns NULL if memory is not sufficient.
   

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

int main()
{
    int n, i, *ptr, sum = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) calloc(n, sizeof(int));
    if(ptr == NULL)
    {
	printf("Error! memory not allocated.");
	exit(0);
    }

    printf("Enter elements: ");
    for(i = 0; i < n; i++)
    {
	scanf("%d", ptr + i);
	sum += *(ptr + i);
    }

    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}

free():


free method in C is used to dynamically de-allocate the memory. 
The memory allocated using functions malloc() and calloc() is not de-allocated on their own. 
Hence the free() method is used, whenever the dynamic memory allocation takes place. 
  It helps to reduce wastage of memory by freeing it.

Syntax: free(ptr); 
Dangling Pointer:- A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

realloc() :



“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a 
previously allocated memory. In other words, if the memory previously allocated with the help of 
malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. 
re-allocation of memory maintains the already present value and new blocks will be 
initialized with the default garbage value.


#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr, i , n1, n2;
    clrscr();
    printf("Enter size: ");
    scanf("%d", &n1);

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

    printf("Addresses of previously allocated memory: ");
    for(i = 0; i < n1; i++)
	 printf("%u\n",ptr + i);

    printf("\nEnter the new size: ");
    scanf("%d", &n2);

    // rellocating the memory
    ptr = realloc(ptr, n2 * sizeof(int));

    printf("Addresses of newly allocated memory: ");
    for(i = 0; i < n2; i++)
	 printf("%u\n", ptr + i);

    free(ptr);

    return 0;
}

structures and pointers in C

Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
   1.Using ( * ) asterisk and dot ( . ) operator.
   2.Using arrow ( -> ) operator 
  
 Program to access the structure member using structure pointer and the dot operator
 
    #include <stdio.h>
	#include <stdlib.h>
    #include<conio.h>
    void main()
    {
    struct Subject
    {

	char subname[50];
	int subid;
	char subduration[50];
	char subtype[50];
    };
	struct Subject sub,*ptr;
	clrscr();
	ptr = & sub;
	strcpy (sub.subname, "PROGRAMMING FOR PROBLM SOLVING USING C");
	sub.subid = 1203;
	strcpy (sub.subduration, "5 Months");
	strcpy (sub.subtype, " Theory & Lab");

	printf (" Subject Name: %s\t ", (*ptr).subname);
	printf (" \n Subject Id: %d\t ", (*ptr).subid);
	printf (" \n Duration of the Subject: %s\t ", (*ptr).subduration);
	printf (" \n Type of the Subject: %s\t ", (*ptr).subtype);

    }
    
Program to access the structure member using structure pointer and arrow (->) operator

    #include <stdio.h>
	#include <stdlib.h>
    #include<conio.h>
    void main()
    {
    struct Subject
    {

	char subname[50];
	int subid;
	char subduration[50];
	char subtype[50];
    };
	struct Subject sub,*ptr;
	clrscr();
	ptr = & sub;
	printf("Enter Subject name");
	gets(ptr->subname);
	printf("Ente subject id");
	scanf("%d",&ptr->subid);
	scanf("%s",&ptr->subduration);
	scanf("%s",&ptr->subtype);
	printf (" Subject Name: %s\t ", ptr->subname);
	printf (" \n Subject Id: %d\t ",
	ptr->subid);
	printf (" \n Duration of the Subject: %s\t ", ptr->subduration);
	printf (" \n Type of the Subject: %s\t ", ptr->subtype);

    }


Dynamic memory allocation of structures

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

int main()
{
struct course
{
int marks;
char sub[30];
};
struct course *ptr;
int i, no;
printf("Enter number of records: ");
scanf("%d", &no);
ptr = (struct course*) malloc (no * sizeof(struct course));
for(i = 0; i < no; i++)
{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->sub, &(ptr+i)->marks);
}
printf("Displaying Information:\n");
for(i = 0; i < no ; i++)
printf("%s\t%d\n", (ptr+i)->sub, (ptr+i)->marks);
return 0;
}

Pointer to pointer in C (Double Pointer)

The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. Such pointer is known as a double pointer (pointer to pointer).
    #include<stdio.h>
    #include<conio.h> 
    void main ()  
    {  
	int var = 100;
	int *ptr1;
	int **ptr2;
	ptr1 = &var; 
	ptr2 = &ptr1; 
	printf("address of a: %x\n",ptr1); 
	printf("address of p: %x\n",ptr2); 
	printf("value stored at p: %d\n",*ptr1); 
	printf("value stored at pp: %d\n",**ptr2); 
    }  
    

1 comment: