Welcome

C Programming Tutorial


C Pointers

Pointer is a variable which points to another variable. Variable holds a value, pointers hold memory address.

Pointers are used to access & manipulate memory directly.

Declaring Pointer variable

Syntax:

	typename *variable;   // type can be any valid 'C' data type. pointer variable   follows same rules as other variables in the program..
Example:
	int *p;  
	char *c;
	float *f;

Asterisk(*) before the variable name,gives the pointer. now p is pointer variable. Asterisk * is a binary operator,used for multiplication in arithmetic operations. In Pointers it is a unary operator,prefended before variable name.
Here i is a pointer variable of type int, which can hold address of integer variables. Similarly

	char *ptr;       //character pointer ,points to string
	float *fptr;     //floating point pointer, points to floating point variable.




Initializing Pointer variable

Initializing pointer variable is mandatory, it must be initialized before using it, In above case i.e int *p; p points to unknown memory location, Refering to unknown memory locations may crash the program.Variable is nothing but a given name to memory location. Its known memory location, Known memory location must be assigned.

There are 2 ways to Intialize or assign pointer variables. to initialize pointer variable , &(ambersand) is a unary operator is used to get the address of the variable. Note:&(ambersand) is a binary operator in bit-wise operations. In Pointers it is unary operator

Method1
-----------
At the time of declaration;

int x=100,*p=&x;
int *p=&x,x=100;Wrong:variable name must be declared first, before refering
Method2
-------------
    Assigning pointer variable

int *p,x;

x=100;
p=&x;

in Both methods p is a pointer variable, which points to type int variable.

In case pointer variable is not pointing to any variable, It must be Intialized as follows

	int *p=NULL;   
	int *p=0x0;
	int *p='\0';

NULL is a macro defition defined in stdio.h second case it can be assigned to 0x0 hexa decimal value, or in Last case with Null('\0') character.

A pointer is not pointing to any thing or pointing to null character is called as a null pointer



Delaing with pointers, uses 2 terms

  • Pointer Referencing
  • Pointer Dereferencing

Pointer Reference means pointing to some variable. for ex: p=&x , p references variable x.

Pointer DeReference means getting the value of variable,which it points to. ex: *p dereferencing the variable



Printing the values using pointers

//printing the address of x and value of pointer variable
int x=10,*p=&x;

printf("%x,%x",&x,p);

format %x used for printing hexadecimal values
&x  gives address of the variable x
p  gives value of the pointer variable p.

%p format specifier also used for printing pointers

printf("%p,%p",&x,p);



Printing the values using pointers

//printing the value of x and value of variable using pointer 

int x=10,*p=&x;

printf("%d,%d",x,*p);

*p  means dereferencing the pointer variable. i.e accessing variable x value using pointer variable.


Changing the value of x using pointer variable

int x=10,p=&x; *p=20; print the value value of x; printf("%d",x); //20


Adding two numbers using pointer variables

int x=20,y=30;

int *px=&x,py=&y;

// we have 2 variables x and y intialized to 20 and 30 repectively,  and 2 pointer variables px and py
initialized to x and y respectively 

 int sum = *px+*py;  //50


Increment or Decrement pointer variables

 
int x=10,*p=&x;
p=p+1; //x is a integer variable,assuming int occupies 4 bytes. p+1 means p is int pointer (4 bytes)+1; its going to point to 5th byte. 
       //in our case 5th byte is unknown address. pointer pointing to unknown address is called as a dangling pointer

//Similaryly for p=p-1   p is int pointer  p-1 means p is pointing to previous 4 bytes location or address. that is also unknown address. 
p=p-1;

//increment using unary operator ++
	int t = ++*p;  //Dererence the pointer value and then increment it. ans:11, ++ operator applies on *p , *p has value 10, ++*p gives  11
	t = *p++;  //Increment p after accessing whatever it point to, so t is 10  and x=10;

Expressions ++*p++

	int x=10,*p=&x;

	int result= ++*p++;

	step1) it dereferences pointer variable , *p
	step2) it preincrements it,  now result=11,
	step3) post increment on pointer, pointer will be incremented by 1.

	print value of x,*p and result

	printf("x=%d,result=%d",x,result); //x=11,p=11,result=11

	Now what is the value of *p

	post increment operator , increment pointer variable by 1, means , pointer now pointing to unknown memory location.
	
	printf(" %d", *p); // gives junk result, i.e every time run the application, unconsistent values will be displaed.

	Note: arithmetic operations on Pointers will work 
			correctly on arrays(static or dynamic). or pointer pointing to same data source   	

Passing Arguments to function using pointers

Passing arguments to function using pointers,reduces the space occupied by arguments

Passing arguments using pointers uses Call-by-Reference technique. using this technique calling function and called function operates on same memory location of the arguments


Increment x value by 1 using pointers

	int x=10;

	void incr(int *p)
	{

		*p=*p+1;
		
		//*p=++*p;
	        //

       		// (*p)++;
		//
	}

	incr(&x);

	printf("x=%d",x);  //x=11

	//call-by-reference    variable x, formal parameter int *p  , both pointing to same memory location.
	//because  in incr(&x) , passing address of variable x,
	//any updation on  pointer variable will gets refected on variable x.

Mulitiply method takes 2 pointer variables

	int mul(int*x,int*y)
	{
		return *x * *y	
	}

	//function call

	int x=10,y=20;

	int result = mul(&x,&y);
	printf("x=%d,y=%d,result=%d",x,y,result); //200

	calling add function with numbers directly gives following error message
	result = mul(10,20);  
	Program received signal SIGSEGV, Segmentation fault. and main() function returns -1

Constant pointers and Pointer to constant

Pointer to Constant pointer is pointing to constant value,but user can change the pointer value.

	const int x=10;
	const int *p=&x;

	const int y=11;
	*p=y; error:assignment of read-only location '*p'
	p=&y; right. p can point to another variable

Constant Pointer user cannot change address of ,what it points to

//constant pointer
   int x=10;
   int *const p=&x;
   int y=11;
   *p=y;//right
   p=&y;error:assignment of read-only location 'p'

Constant Pointer Pointing to Constant

User cannot change variable value or doing any arithmetic operations on that variable

User canot address of pointer,once it is being intialized,

const int x=10;
const int *const p=&x;
const int y=11;
 The following all operations will fail
*p=y; //Cant change constant variable x value using pointer p p=&y //p cannot point to any other memory location x=y; // x is a constant,


Arrays and Pointers

     Arrays occupy contguos memory locations. Their addressess increases from Lower index to higher index. i.e Higher index has higher address compared to lower index Address.

Accessing One-Dimensional Arrays using Pointers

     How to access One-Dimensional array elements using pointer variables.
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *pa=a;
//here "a" contains the base address of the array. user assigns base address of the array to pointer "pa".
The same thing can be re-written int *pa=&a[0];
now pointer variable pa points to zeroth element of array "a" .Both are same.

Using this type of syntax ,pointer can point to any location in the array

int * pa = &a[5]; //ponter variable points to 5th index of the array.

		int *pa=a;
		
		//print zeroth element
		
		printf("%d",*p);  prints element at zero index.
		
		pa=pa+1;  //pointer is incremented by 1, Assuming int takes 4 bytes , array base addr is 2000, p+1 points to 2004 memory location.

		//writting p=p+1 using unary operators ++.

		printf("%d", *(++pa));   // unary operators ++ and * are evaluated from right to left  
		increments the pointer variable by 1 then prints the value. now "pa" points to 1st index in the array.

		doing arithmetic operations on Base Address of an Array

		++a; --a,a++,a--  gives error: lvalue required as increment operand
		 User cannot change base address of an array

printing array elements using pointers

int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int i=0;

int *pa=a;

while ( i < sizeof(a)/sizeof(int)){

    printf("%d ",*pa);
    pa=pa+1;
    i++;
}

Passing array to a function using pointers!


Pointers to Pointers

       Pointer is a variable which holds computer memory location. pointer to a pointer is a variable which holds address of another pointer variable.

	int a = 20;
	int *p = &a;
	int **pp = &p;
 use ** double indirection operator for pointer-to-pointer. 
"pp" is a pointer to pointer variable which holds address of pointer "p" 	

	//update variable "a" value using double pointer 

	**pp=30;
	printf("%d",a);  //prints 30





Accessing Two-Dimensional Arrays using Pointers



Function Pointers

Every token has address in C programming. So Every function also has address. You can get address of the function, can assign it to pointer.

Using function pointers ,user can invoke functions.

Function pointer syntax:
		type *(function pointer name)([optional arguments]);
	
Function Pointer example:
		int *(pf)();

		//pf is a function pointer, it can point to any function which accepts no arguments and returns int value.
		//Note: Asterisk (*) is a prefix operator and it has lower precedence than ().
so parenthesis are necessary for function pointer declartion
	

simple call to function pointer
	int add(){return 10+20;}
	int div(){return 20/10;}
//declaring function pointer. function return int and takes zero arguments.
	int (*fp)();  

//assigning function pointer with function;

	fp=add();   At this point no function call is made. just assigning address of the function to function pointer

	//print the result
	printf("calling add method=%d",pf);   //30	  at this point , pf function pointer, calls method add,and result will be returned to printf function
	
	pf=div();// now assign address of div function to function pointer.

	printf("calling div method %d",pf);   //2	, function pointer calls div method

	int rem(int x,int y){return x%y;}

	//declaring function pointer which accepts 2 int params and return int.

	int (*fp)(int,int);

	fp=rem(10,20);  //assigning function to  function pointer.
	
	//calling function using function pointer.

	fp(10,20);  //10  


Count no. of lines in a Given String

char * ptr="Hello \n Are you there\n How you been?";

count(ptr);  /*Gives no of lines in a given string */
int count(char *p)
{
	int nl = 1;
	
	while(*p != NULL)
	{
		if(*p =='\n') ++nl;
		p=p+1;
	}

return nl;

}


Count Number of Vowels in a Given String



    char * ptr="Hello \n Are you there\n How you been?";

    int cv= countVowels(ptr);
    printf("No of Vowels %d\n",cv);

int countVowels(char*p)
{
    int nv=0;
    char *vowels="aeiou",*tv=vowels;
    char c;

    while (*p != NULL){
    if(*p >= 65 && *p <= 90) c=*p+'a'-'A';
    
    else c=*p;
        while(*tv++ != NULL){
            if(*tv == c) ++nv;
        }
        tv=vowels;
        p=p+1;
    }

    return nv;
}

/*  output: No of Vowels 12 */

Pointer Example

Write a program that takes three variable (a, b, c) in as separate parameters and rotates the values stored so that value a goes to b, b, to c and c to a.

        int a=10,b=20,c=30;
        printf("Before rotate a=%d,b=%d,c=%d\n",a,b,c);
        func(&a,&b,&c);
        printf("After rotate a=%d,b=%d,c=%d\n",a,b,c);

	void func(int *a,int *b,int *c)
	{
		int t = *b;
		*b=*a;
		int t2 = *c;
		*c=t;
		*a=t2;
	}

output:
Before Rotate:a=10,b=20,c=30
After Rotate:a=30,b=10,c=20


ADS