Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Sep 25, 2015

Programs that work in C and not in C++


1.
int main()
{
                       int a = fun();
            return 0;
}
int fun()
{
            return 2;
}

As the function prototype is not declared before the function is called, it gives an error in C++. But in C, it works fine.
2.
int main()
{
            const int a;                
            return 0;
}
               
            In C++, the const integer should be initialized at the time of declaration only.
3.
int main()
{
            int c;
            void *b=&c;
            *((int*)b)=10;
            printf("%d",*((int*)b));
return 0;
}

Here the void pointer points to an integer.  For typecasting to int pointer, we need not to use                 explicit type cast as we do in C++. In C, type casting is done through implicit typecast.
4.
int main()
{
            int const a=10;
            int *p=&a;
                       return 0;
}

In C++, only the const pointer can point to the const integers. In C, either const or non-const pointers can point to that object.
5.
int main()
{
            int new =10;
printf("%d",new);
return 0;
}

In C++, new, delete, explicit are Reserved words. As reserved words cannot be used as variables in C++.
6.
int main()
{
            char *p=333;
            printf("%u",p);
            return 0;
}


            In C++, char pointer  can’t point  to an integer variable.


      Also see 

                       1.  4 Pillars of OOP concepts
                       2.  Associativity of Operators 
                       3.  Graph Terminology



Filed under ,  | 

Aug 9, 2015

What’s the difference between malloc(),calloc() and realloc() ?


        In c language there are 3 terms that are used for dynamic memory allocation. If we allocate the data through dynamically, then that would be available until the program terminates (like global variables).

        we can have choice when to allocate and de-allocate. De-allocation can be done using free() function.
1) Malloc() :
        
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.

                void *p = malloc(sizeof (int))
  • As it a void pointer, we can’t directly dereference it .

                like *p = 2;      // gives an error.
        
  • Before using, we have to typecast to the system defined data types ( int, float, char etc ).


        int *q = (int* )p ;
        *p = 10;           // no error

  • After allocating the memory, if we won’t initialize the values, then garbage values will be present.



         
Calloc() :
        Calloc() also allocates the blocks of memory and also initializes the allocated memory to value equal to 0 ( like in malloc() garbage values will be present). It also takes 2 function arguments as inputs.

        1) Number of blocks.
        2) Size of each block.

                int *p = (int*) calloc(n, sizeof(int))

Example:
int *p = (int*) calloc(25, sizeof(int))

This statement allocates contiguous memory space for an array of 25 elements each of size of int, i.e. 4 bytes.
  • calloc can be defined using malloc function as follows :

                char *p = (char*) (10* malloc( sizeof(int)));
                memset(p, ’0’ , 10);

The 10 memory address locations will have value 0.
Realloc() :
        realloc() is used to reallocate the memory for the given pointer either to increase the memory block or decrease the memory  block.

Syntax :

                int *b = (int*) realloc( oldblock, new memorysize);
  • It first looks whether the old block can be extended if we want more memory. If it is not possible, then a new block of memory is allocated and the old values are copied.
  • After copying the old block of memory into the new memory location, old one is automatically deleted.

  • If we reduce the size of memory block, then remaining memory is de-allocated automatically.
  • free() statement can also be done using realloc().

int *b = (int*) realloc(b, 0);
  • malloc() function can be done using realloc().


int *b = (int*) realloc(NULL , n*sizeof(int) );

SEE ALSO :






Filed under ,  | 

Jul 2, 2015

TYPEDEF - create variables by your name

Typedef:
          Typedef is a keyword used to assign new names to existing data types. This is same like defining alias for the commands.

typedef  existing_name alias_name;

After this statement, instead of existing_name we can use alias_name.
If we look at an example

          typedef int aj;
aj i , j;

The above statement define a term  aj  for an int type. Now this  aj  identifier can be used to define int type variables. This is also equal to int i , j;

          typedef unsigned long  int  ajj;
        ajj  i, j ;

After this type definition, the identifier ajj can be used as an abbreviation for the type unsigned long int.

Using typedef with structures :

You can use typedef to give a name to user defined data type as well. For example you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:

typedef struct book
{
           int x;
           float y;
           char c[10];
} Book;
         
         Here Book is the structure_variable name and book is tag_name. After this definition, we can create structure variables with Book word instead of struct book.

For example:

 #include <stdio.h>
 #include <string.h>
 typedef struct Books
 {
          char title[20];  
          int pages;
 } Book;
int main( )
           {
           Book  book;
           strcpy (book.title, "C Programme");
                     book.pages = 230;
                     printf( "Book title : %s\n", book.title);
           printf( "no of pages : %d\n", book.pages);
                     return 0;
           }

In the above program we have defined Book book instead of struct books book.

·       Typedef can be used for pointers also.

                    typedef int *x , y;

By this definition, we can use x for defining pointer variables and y can be used for integer variables.

#include <stdio.h>
 #include <string.h>
int main( )
     {
              typedef int  *x , y;
              y  a = 10;
              x  b;
              b = &a;
              printf("%d",a);              //output : 10 10
              printf("%d",*b);
               return 0;

     }
Filed under ,  | 

Jun 23, 2015

EXTERN -- wherever u define variables, it will get access to use them

Extern :

All variables we have seen so far have limited scope (the block in which they are declared) within the program. However, in some applications it may be useful to have data which is accessible from within any other file or which remains in existence for the entire execution of the program.

Suppose if a variable is declared in file1 and we want to access the variable in another file2 and file3, then how to access these variables in other files??? Simple, the answer to this is “Extern”.

Extern keyword is used for the global variables that are defined in one file and can be used those variables in other files by using extern keyword.

extern int a;

Let us see an example:

file1.c                                                                 file2.c

#include<stdio.h>              #include<stdio.h>
int main()                     int a=1;
{                              int main()
    extern int a;              {return 0;}
    printf("%d",a);
    return 0;

}

            In this example, the variable ‘a‘ is created and initialized in file2.c and is used in file1.c as external variable. For information on how to compile a program whose source code is split among multiple files, you can simply type the command gcc -o a file1.c file2.c, and run the program with ./a.

·       When you use extern keyword before the global variable declaration, the compiler understands you want to access a variable being  defined in another program or file, and hence not to allocate any memory for this one. Instead, it simply points to the global variable defined in the other file.
  a)
#include <stdio.h>
extern int i;    //extern variable
int main()
{
    printf("%d",i);
    return 0;
}

Output: Compilation error, undefined symbol i.
        
            b)
         #include<stdio.h>
extern int i;
int main()
{
    i = 1;
    return 0;
}

This program throws error in compilation. Because ‘i’ is declared but not defined anywhere. Essentially, the ‘I’ isn’t allocated any memory. In (b), the program is trying to change the value to 1 of a variable that doesn’t exist at all.

·       If the global variables are not initialized then, they are initialized to their default values.
Int – 0 , Float – 0.0, Char - 0 , String – null

#include <stdio.h>
int i; char c; float f; char *str;  
int main()
{
    printf("%d %d %f %s",c,i,f,str);
    return 0;
}
 
Output: 0 0 0.000000 (null)
 
·       If we declare a variable as extern, it means that the definition for that variable is defined somewhere else in the program or in other file. It doesn’t allocate the memory for these variables. It’s just the declaration. So we can declare it as many times as we can. 
 
#include <stdio.h>
extern int i;        //Declaring the variable i.
int i=1;             //Initializing the variable.
extern int i;        //Again declaring the variable i.
int main()
{
    extern int i;     //Again declaring the variable i.
    printf("%d",i);
    return 0;
}
 
Output: 1
 
·        A particular extern variable can be declared many times but we can initialize at only one time. (even outside or inside the function of same program)

#include <stdio.h>
extern int i; //Declaring the variable
int i=25;     //Initializing the variable
int main()
{
    printf("%d",i);
    return 0;
}
int i=20; //Initializing the variable
 
Output: Compilation error: Multiple initialization                 variable i.
 

·         To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables.

#include <stdio.h>
extern int i=1;    //extern variable
int main()
{
    printf("%d",i);
    return 0;
}
 
Output: 1
 
·        We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally.
a)
#include <stdio.h>
int main()
{
    extern int i=1;   // Try to initialize extern variable
                     // locally.
    printf("%d",i);
    return 0;
}
 
Output: Compilation error: Cannot initialize extern variable.
b)
 
#include <stdio.h>
int main()
{
    extern int i;    // Declaration of extern variable i.
    int i=1;         // Try to locally initialization of
                       // extern variable i.
    printf("%d",i);
    return 0;
}
 
Output: Compilation error: Multiple declaration of variable i.


Filed under ,  |