Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Thursday, 3 August 2017

Pointers


In any programming language the variables are stored in some memory locations with some addresses.Some programming languages like c,provides a way for accessing these memory locations .This facility is provided with a well known concept called pointers.So,lets look at pointers

What is a pointer?

Most of the programmers feel pointers as difficult but its little bit tricky.Inshort,pointers are the variables that can store address of another variables. lets define a pointer

int *p;

The above declaration confirms that p is an integer pointer.* is used to indicate a variable as a pointer variable.

Example

int main()
{
 int *p,a=10;
 p=&a;
 printf("The address of a is %d\n",p);
 printf("The value of a is %d%",*p);
}

Output

The address of a is 339631052
The value of a is 10

From the above code,it is clear that the address of variable a is stored in p.address operator(&) is used to get the address of a variable.* is a dereferenceing operator used to retrieve the value stored in the address location.

Arithmetic operations on pointers:

The following are the invalid arithmetic operations on pointers.

  • Addition
  • Multiplication
  • Division
  • Modulo

The above operations are invalid because pointers contain addresses so performing the above operations on pointers results meaningless results. However,Subtraction is legal among pointers as it results to the offset between the addresses.

Interesting concepts of pointers


Pointer array vs array of pointers


pointer array


Pointer array is a pointer pointing to an array.
int main() 
{
 int *p,arr[5],i;
 p=&arr; // p is pointing to array arr
 for(i=0;i<5;i++)
 {
     scanf("%d",&arr[i]);
 }
 for(i=0;i<5;i++)
 {
     printf("%d",*(p+i));
 }
    return 0;
}

Output

12345

Array of pointers

Array of pointers is an array containing addresses as array elements.

   
int main()
{
 int *arr[5],i;
 for(i=0;i<5;i++)
 {
  arr[i]=&i;
 }
 for(i=0;i<5;i++)
 {
  printf("%d\n",*arr[i]);
 }
}

Output

0
1
2
3
4

function pointer vs pointer to function


pointer to function


Function pointer is a pointer typically points to the block of executable code.

Example

void code(int i)
{
 printf("value of i is %d",i);
}
int main()
{
 void (*fun_ptr)(int)=&code;
 (*fun_ptr)(5);
 return 0;
}

Output

value of i is 5

Here we need an extra bracket around function pointer like fun_ptr,otherwise it becomes void *fun_ptr*(int) which is a function returning pointer.

function pointer

function pointer is function that returns pointer.

int *fun();
int main()
{
    int *ptr;
    ptr=fun();
    printf("%d",*ptr);
}
int *fun()
{
    int *pointer=malloc(sizeof(*pointer));
    *pointer=10;
    return pointer;
}

Output

10

Tuesday, 16 May 2017

Storage Classes

Storing the data for execution is the heart of the programming.What actually matters is accessing the stored data.So,lets See how to perform these interesting tasks...

What is scope and life time of variables?


 Scope of a variable is actually the area of our program where we can access our variables.
 life time of variable is the time for which the variable has a valid memory.

What is storage class?


Any variable/function that exists inside the program will have scope and life time.This scope and life time of variables is described through storage class.

we have four storage classes.


1)auto
2)extern
3)static
4)register

Sunday, 19 March 2017

Segmentation fault

In the journey of programming,we may come across many errors.Let us discuss one of the most frequently facing error Segmentation fault.

What is Segmentation Fault?


Segmentation means addressing space in memory.Therefore,segmentation fault means fault in addressing memory i.e., illegal accessing of memory. It occurs when the hardware detects an attempt to refer a non existent segment or a location that is out of bounds of segment.

Let us see some of the scenarios.


Example 1:


segmentation fault may occur due to improper scanf statement.
main()
{
int a;
scanf("%d",a); // error missing '&'
}

Saturday, 18 March 2017

error : lvalue required!!!!

One of the frequently facing error in programming is "lvalue required" so,lets discuss about some of the important points to handle those errors.

What is l-value


Every expression has l-value and r-value.l-value represents the memory location where an identifier or value is stored. r-value may be an expression or just a value that is stored in the memory.

Example :


consider the expression
var=5
 var   ->  l-value.
 =     ->  assignment operator.
 5     ->  r-value.
l-value refers to the memory location ,thus they must me variables.
There are many instances,where we get errors due to l-values of the expression.

Example 1:


l-value of an expression cannot be constant value.
int main()
{
  int var;
  2=var; //error.
  return 0;
}

Thursday, 16 March 2017

See For 'C' Errors !!!

Error may be the most common word that irritates most of us.So, lets see some of the most common errors in programming and some tips to fix them.

what is an 'error':


errors are also known as bugs that causes the program to either run unexpectedly (shows unexpected result) or prevent the execution of a program.

Types Of Errors:



  • Syntax Errors (Compiler errors or Compile-time errors)

  • Semantic Errors.

  • Logical Errors.

  • Linker Errors.

  • Latent errors.

  • Runtime Errors.

SYNTAX ERRORS


Syntax errors represent grammar errors in the use of the programming language. These usually occur at compile-time.

Some of the examples of the Compiler errors are:


  • Misspelled variable ,function names and Missing semicolons
  • Unmatched parentheses, square brackets, and curly braces
  • Using a variable that has not been declared
  • Incorrect format in selection and loop statements

Example


 
 void main()
 {
 int  a=10         // Syntax error as semicolon is missing
 int  b=100 : // Syntax error as using ':' instead of ';'
 c=a+b;       //Syntax error as c is undeclared
 }
}            //Syntax error for unbalanced parenthesis

TIPS TO FIX :-


Syntax errors are the easiest to find and fix. Over the years, compiler developers have worked hard to make compilers smarter so that they can catch errors at compile time that might otherwise turn out to be run time errors.

Semantic Errors


These are valid code the compiler understands, but they do not what you, the programmer, intended. These may be using the wrong variable, the wrong operation, or operations in the wrong order. There is no way for the compiler to detect them.

Example :

 
void main()
 {
 int  a+b=c;         // Semantic Error
  int c=a+b;   //correct one
 int  a=+b;          // Semantic Error
  int  a+=b;   //correct one
 }

Logical Errors:


As the name itself implies, these errors are related to the logic of the program. Logical errors are also not detected by compiler and cause incorrect results.

Why do we get Logical errors:


These errors occur due to incorrect translation of algorithm into the program or occurs due to poor understanding of the logic

Logic errors are the hardest to find and fix because:



  • These errors cannot be found by the compilers.
  • Program executes normally,but results in unpredictable outputs.
  • Program may give correct results for only certain set of inputs.


Examples:

 
void main()
{
float a,b;
printf("enter the values of a and b :- ");
scanf("%f %f",&a,&b);
if(a==b) // When a and b are float types values, they rarely become
            equal due to truncation errors.
printf("these two are equal");
}

TIPS TO FIX :


Never use any relational operator while dealing with floating point integers.

Linker Errors:


Linker errors usually occur when there are certain necessary files that are not linked for successful execution of the program.These are mostly occur when we do not include header files for the predefined functions used in a program and when we misspell a standard c function.

Example 1:


 
 void mian()       // Linker error as 'main' is misspelled as 'mian'
 {
 printf("welcome to code titans ");
 }

Example 2:


 
 #include"stdio.h"
 void main()
 {
   int x,res;
  printf("enter the value of x");
  scanf("%d",&x);
  res=pow(x,2);     //linker error as pow is declared without using header file math.h
  printf("square of x is %d",res);
  } 

However,some compilers add certain necessary header files by themself that do not cause error

TIPS TO FIX:


Check whether the necessary files are included in the program or not.

Latent errors :


Latent Errors are the hidden errors that occur only when a particular set of input is given.

Example:


result = (a+b)/(c-d);
Here,an error occurs only when c and d are equal because that will make remainder zero (divide by zero error).

TIPS TO FIX:


Be clear,about the logic of the program and consider all possible combinations of input data to detect the errors.

Runtime Errors:

Runtime errors are the errors that occur during the execution of the program.

Some examples are:


  • Dividing any number by zero .
  • Insufficient memory for dynamic memory allocation.
  • Referencing an out-of-range array element.etc

These are not detected by compiler while compilation process. A program with these kinds of errors will run but produce erroneous results or may cause abnormal termination of program. Detection and removal of a run-time error is a difficult task.


Examples of some illegal operations that may produce runtime errors are :


  • Dividing a number by zero
  • Trying to open a file which is not created
  • Lack of free memory space

Example :

 
void main()
{
int a=10,b=0,result;
int number;
result=a/b;                   // Runtime error
scanf("%d",&number);     
}

Saturday, 11 March 2017

extern Keyword

Let us discuss one of the interesting c-keyword extern.Most of us are not aware about extern keyword as we do not use it frequently. To be clear,we are using extern key word unknowingly in our c programs.
For better understanding of extern, it is required to know about declaration and definition.

Declaration vs Definition


Declaration simply declares that variable/function exists some where in the program.
In case of variables,declaration gives information about the datatype of variables.In case of functions declaration gives info about the type of arguments,no.of arguments and return type of function.One of the important thing is to be noted is No memory is allocated for any variable/function in its declaration session.
In addition to declaration,Definition includes allocating memory for variable/function. extern is mainly used to extend the scope of variable/functions.

Use of extern w.r.t C-functions


By default all the functions use extern i.e., both definition/declaration of C functions include extern keyword.

Example:

int functionA(int arg0,float arg1,char arg2)
The compiler treats the above declaration as:
extern int functionA(int arg0,float arg1,char arg2);

Friday, 3 March 2017

Recursion

Let us discuss one of the widely used method of solving certain class of complex problems.Popularly known as “Recursion”.

What is Recursion?

Recursion is nothing but a function calling itself.The basic idea of recursion is breaking a complex problem into pieces and solving those individual problems and combining the result. We use recursion when there are some set of statements that are to be executed many times.

Basic Idea of Recursion

main ()
{
functionA();
}
functionA();
{
-----statements----;
functionA();
}
There are certain points that are necessarily important in designing a recursive algorithm.

Base condition:

It is an instance of a problem,the solution of which requires no further recursive calls is known as base case. Usually this condition exists in if statement.

Recursive formula:

Every Recursive function contains recurrence formula.This recurrence formula enables us to perform some task many times.