The greatest mistake you can make in life is to be continually fearing you will make one

Saturday, 29 May 2010

Pointers In C

Pointers:
     Pointer is a variable contain the address of another variable. If a variable contains address of another variable than it is said that first variable points to second. All operation perform on pointers are done through two operators '*' and '&'. '&' is a unary operator that returns a memory address of a variable. '*' is complement of '&' and return value stored at a memory location stored in a pointer. '*' can interpreted as statement "at address" while '&' can be interpreted as statement "address of".

Pointer Declaration:
      Declaring a pointer variable is quite similar to declaring a normal variable all you have to do is to insert a star '*' operator before it.General form of pointer declaration is -
datatype* name;
where datatype represent the type of data  to which pointer thinks it is pointing to.
Multiple pointers of similar type can be declared in one statement but make sure you use * before every one otherwise they will become a variable of that type.
Example:
    int *p;
    float *f1,*f2;
    char *ch;

Pointer Assignment: 
     Once we declare a pointer variable we must point it to a value by assigning the address of the variable 
Example:

    int *p;
    int x;
    p=&x;

     The value of one pointer can be asssigned to another pointer using assignment operator '=' . In this value of right hand side points to memory address of variable stored in left hand side pointer. As a result both pointers point to same memory location after this expression.
Pointer of similar type can be used in expression easily as shown below but for diffrent type pointers you need to type cast them as shown in next section.
#include < stdio.h >
int main ()
{
char ch = 'x';
char *c1, *c2;
c1 = &ch;
c2 = c1; // Pointer Assignement Taking Place
printf (" *c1 = %c And *c2 = %c", *c1,*c2); // Prints 'x' twice
return 0;
}

Pointer Conversion
       Before concept of pointer conversion you must understand the concept of a void pointer. Void pointer technically is a pointer which is pointing to the unknown. Void pointer has special property that it can be type casted into anyother pointer without any type casting though every other conversion needs an type casting. In dynamic memory allocation function such as malloc ( ) and calloc ( ) returns void pointer which can be easily converted to other types.
       Also there is a pointer called null pointer which seems like void pointer but is entirely diffrent. Null pointer is a pointer which points to nothing. Null pointer points to the base address of the CPU register and since register is not addressable usage of a null pointer will lead to crash or at minimum a segmentation fault.
       Also be careful while typecasting one pointer to another because even after type casting your pointer can point to anything but it will still think it is pointing to something of it declared type and have properties of the orignal type.
      Type conversion is a powerful feature but yet it may lead difficult to remove bugs and crashes,it may also lead to unexpected and unreliable results but program would compile succesfully.
Code below shows a type casting of one pointer into another -
#include < stdio.h >
int main ()
{
int x=10;
char *ch;
int *p;
p = &x;
ch = (char *) p; // Type Casting and Pointer Conversion
printf (" *ch = %c And *p = %d", *ch,*p); // Output maybe unexpected depending on the compiler.
return 0;
}

Pointer Expressions:
    Like normal variables pointer variable can be used in expressions.
Example:consider 2 integer pointers p1,p2
    int *p1,*p2;
    int x,y,z,k;
    p1=&x;
    p2=&y;
    z=*p1**p2;
    k=k+*p1;
    z=10**p2/*p1;



Pointer Arithmetic
     Pointer arithemetic is quite diffrent from normal arithemetic. Not all artihemetic operations are defined in pointers. You can increment them, decrement them, add and subtract integer values from them. You even can subtract two pointers.But you cannot add two pointers, mulitply, divide,modulus them. You can not also add or subtract values other than integer.

Address+Number=Address
Address-Number=Address
Address++=Address
Address--=Address
     Now consider a pointer X , its current value that address it is pointing to is 1000 (just assuming).We make another assumption about the size of the data types. Size of data type is machine dependent, for example int can be 2,4 byte depending upon the compiler.
Now if this X pointer is char type(assumed 1 Byte ) then X++ will have value 1001 and X-- will have value 999. Now if this X pointer is integer type (assumed 2 byte) then X++ will have value 1002 and X-- will have value 998. Again if this X pointer is float type (assumed 4 Byte) than X++ will have value 1004 and X-- will have value 996. Also if this X pointer is double type(assumed 8 Byte ) than X++ will have value 1008 and X-- will have value 992.
     when you increment a pointer of certain base type it increase it value in such a way that it points to next element of its base type. If you decrement a pointer its value decrease in such a way that it points to previous value of its base type.
      You can add or subtract any integer value, in such case value of pointer get increase and decrease by the product of the value to be added or subtract and size of the base type. Pointer of user defined types such as structures and union also increase by the quantity of thier bit values which can be determined using sizeof operator.

Pointer Comparison:
         Two pointers can be compared no matter where they point. Comparison can be done using <, >, =, <= and >= operators. Though it is not forcibly implied but comparison of two pointers become sensible only when they are related such as when they are pointing to element of same arrays.Comparison of two unrelated pointers is unpredictable and your code should not rely upon it. All comparison are generally done on basis of memory organization in the host machine.
Following C source code shows pointer comparison in C -
#include < stdio.h >
int main ()
{
int data[10],i;
int* p1,*p2;
for (i = 0; i <10;i++)
{
data[i] = i;
}
p1 = &data [1];
p2 = &data [2];
if (p1 > p2)
{
printf ("p1 is greater than p2\n");
}
else
{
printf ("p2 is greater than p1\n");
}
}
output:p2 is greater than p1

Sunday, 23 May 2010

Assertion in C

An assertion is a 'conditional check' placed in a program to indicate that the developer thinks that the condtion has to be always true, at that place, for the program to work properly after that point. If the condition happens to be false, the program execution would be abruptly abhorted.

For example:


    assert (y!=0); /* The developer thinks that y shouldn't be equal to 0. If not, the code would get abhorted */
    z=x/y;
Whenever the program gets aborted because of an assertion, a corefile would be dumped. The developer can analyze the corefile (using any debugger, for example 'GDB') and pin-point the exact location of the failure, and then figure out why something unexpected happened. Thus assertions can be very useful for the developer during the early stages of development of a program.

Note that assertions would be enabled only during development and early stages of testing; they would be normally disabled during final testing. Assertions would always be disbaled when the final product is delivered to the customer.

How assertions are different from error handling

Assertions should be used to document logically impossible situations and discover programming errors— if the "impossible" occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is unwise: assertions do not allow for recovery from errors; an assertion failure will normally halt the program's execution abruptly. Assertions also do not display a user-friendly error message.

What is assert()?
Assert() is a macro defined in assert.h, as follows
        void assert (int)
If the value (normally the result of the expression) passed is non-zero, nothing happens. However if the value happens to be zero, it prints an error message similar to the following one to STDERR and aborts the program

Assertion Failed: file line :

Normal uses
The simplest and most effective use of assertion is to specify and check input conditions to functions such as to check
  • Pointers are not null
  • Indexes and size values are non-negative and less than a known limit
Turning assertions off:
  • By default,ANCI C compilers generate code to check assertions at run time.
  • Assertion checking can be turned off by defining the NDEBUG flag to the compiler.
  • This can be done either by inserting #define NDEBUG in a heder file such as stdhdr.h or while compiling use the option -dNDEBUG as
          gcc -dNDEBUG filename

Example

#include <stdio.h>
#include <assert.h >
int main()
{
    int x,y,z;
    printf("Enter the 2 numbers to divide\n");
    scanf("%d %d",&x,&y);
    assert(y!=0);
    z=x/y;
    printf("x/y=%d\n",z);
    return;
}

Output:
Enter the 2 numbers to divide
3 0
Sample1: assert_test.c:8: main: Assertion `y!=0' failed.
Aborted

In this program if the user provides the value 0 for y, then assert() would get triggered and will abort the program.

Best Practice:
 The following code

    assert(y!=0);
    z=x/y;
can be better written along with a string indicating what is the reason for the assertion, as

    assert(y!=0 && "y (denominator) cannot be zero");
    z=x/y;

Question: Whats wrong with this code

#include <stdio.h>
#include <assert.h>

void main () {
    char *my_str[]={"This", "is", "a", "string"};
    int index=0;
    while (index<4) {
        assert (++index && my_str[index-1]);
        printf("%s ", my_str[index-1]);
    }
    printf("\n");
}

Answer: When the code is compiled with assertions deisabled, index variable wouldn't get incremented and would result in an infinite loop. So never write any real code within an assert statement

Thursday, 20 May 2010

Questions on Command Line Arguments

  1. What is command line argument?
  2. Are variables argc and argv are local to main?
  3. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to function?
  4. Is there any way to expand any wildcard characters present in the commandl ine arguments? If yes state that?
  5. What is the maximum length of command line arguments including space between adjacent arguments?
  6. What is 'c, and 'v' in argc and argv stand for?
  7. What is the output of the following program?
      #include < stdio.h >
    int main(int argc,char *argv[])
    {
        int i;
        argc=2;
        argv[0]="";
        argv[1]="I am a dog.Hope I am right";

        printf("Number of Arguments passed=%d\n",argc);
        for(i=0;i< argc;i++)
            printf("argv[%d]=%s\n",i,argv[i]);
        return;
    }
  8. Does the following program has any error or not?
    #include < stdio.h >
    int main(int argc,char *argv)
    {
        int x;
        x=sum(argv[1],argv[2]);
        printf("x=%d\n",x);
        return;
    }
    int sum(int x,int y)
    {
        return x+y;
    }
  9. What type is argv?
    A. char *
    B. int
    C. char **
    D. It's not a variable
     
  10. What does the argument count variable store?
    A. the number of arguments
    B. the number of arguments plus one
    C. the number of arguments minus one
    D. The total size of the argument array
     
  11. In what order do the two command line variables appear in the definition of main? A. Count then argument array
    B. Argument array then count
    C. They don't appear in the definition of main
    D. There is only one argument.
     
  12. What is argv[0]? A. The number of arguments to the program
    B. The name of the program
    C. The first argument to the program
    D. This syntax is illegal 

  13. What variables stores the number of arguments to a program?
    A. argc
    B. argv
    C count
    D. arglen





Tuesday, 18 May 2010

Command Line Arguments

  • Getting the arguments from command prompt in c is known as command line arguments.
  • Command line is that it consists of a sequence of words,typically separated by whitespace.Main program can receive these words as an array of strings,one word per string.
  • main function will accept 2 parameters ,argv and argc
  • argc will be the count of the number of strings given on the command line.
  • argv will be the array of the arguments.since each word is a string argv is an array of pointers to char
  • Example:
        int main(int argc,char *argv[]){......}
  • The strings at the command line are stored in memory and address of the first string is stored in argv[0],address of the second string is stored in argv[1] and so on.
  • we can give any name instead of argv and argc
    Example:
       main(int count,char*str[]){.....}
  • Example Program
    #include<stdio.h>
    int main(int argc,char *argv[])
    {
        int i;
        printf("Number of Arguments passed=%d\n",argc);
        for(i=0;i<argc;i++)
            printf("argv[%d]=%s\n",i,argv[i]);
        return;
    }
    Output
    sunitha@sunitha-laptop:~/ds$ ./a.out g h k
    Number of Arguments passed=4
    argv[0]=./a.out
    argv[1]=g
    argv[2]=h
    argv[3]=k
Command Line Arguments  in Unix/Linux:
  • Most Unix/Linux applications lets the user to specify command-line arguments (parameters) in 2 forms

      * Short options
      consist of a - character followed by a single alphanumeric character
      for example for listing the files the command is ls -l
      * Long options (common in GNU applications)
      consists of two - characters (--)  followed by a string made up of letters, numbers, and hyphens.
  • Either type of option may be followed by an argument.
  • A space separates a short option from its arguments
  • Either a space or an = separates a long option from an argument.
  • GNU C provides 2 functions, getopt and getopt_long to parse the command line args specified in the above format
  • getopt - supports parsing only short options
  • getopt_long - supports parsing of both short and long options.

    In this blog, we would focus only on getopt_long function to parse both long and short options.
 getopt_long()
  • This function is defined in getopt.h

    Syntax:
    -------
    int *getopt_long* (int argc, char *const *argv, const char *shortopts, const struct option *longopts, int *indexptr)

    Usage:
    ------
     while (getopt_long (argc, argv, shortopts, longopts, index) != -1) {
     }

    Parameters
    ----------
    argc and argv are the command line args passed to main
    shortopts:  This is a string containing all the valid short option characters
               An option character can be followed by
                   a colon (:)  to indicate that it takes a required argument. (or)
                   2 colon (::) to indicate that its argument is optional                                                              shortopts can begin with a + to indicate that getopts_long should stop processing on sensing an unexpected arg
               Ex: If we have have a program that can accept the short args -a and -b, the option string would be "ab"
                   Now, if we have to force a mandatory required parameter for -a, but not for -b, the option string would be "a:b::"

    longopts: This is a array of structure, containing the following fields
                   char * , int , int* , int
    long option string  - The command line parameter in long format
                       type                - one of no_argument, required_argument or optional_argument
                       flag                - Set it to null for non-flag parameters
                                             For flag, set it to the address of an int, which should get set when the flag is mentioned in the cli
                       val                 - For flags, set it to the default value the flag should be initialized to
                                             For non-flags, set it to a number, that would uniquely identify this option
               The array has to be terminated with all zeros

            

Monday, 17 May 2010

C Programs based on Command Line Arguments

  1. Write a program to read a text file provided at command prompt and print the content of the file
  2. Write a program to read a text file provided at command prompt and print each word in reverse order For example if the file contains WELCOME TO C output should be C OT EMOCLEW

  3. Write a program using command line arguments to search for a word in a file and replace it with the specified word.The usage of the program is shown below
    C > change < oldword > < newword > < filename >
  4. Write a program that canbe used at command prompt as a calculating utility.The usage of the program is shown below.
    C>calc < switch > < n > < m >
    where n and m are 2 integer operands. switch can be any one of the arithmeticor comparison operators. If arithmetic operator is supplied,the output should be the result of the operation.If comparison operator is supplied then the output should be True or false

Wednesday, 12 May 2010

Questions on Structures

  1. What is a structure?
  2. How to access structure members?
  3. How to access the variable x in the following structure?
      struct s1{ struct { struct { int x; }s2 }s3 }s;
  4. Can structure contain pointer to itself?
  5. Difference between Structure and Unions?
  6. Difference between Structure and Arrays?
  7. How are structure passing and returning inplemented by compiler?
  8. How can we check whether contents of two structure variables are same or not?
  9. How can we read/write from/to data files?
  10. What are the similarities between structure,union and enumeration?
  11. Define bitfields?What is the use of bitfields in structure declaration?
  12. What are the advantages of using Structure?
  13. How will you pass a structure to a function?
  14. How will you pass an array of structures to a function?
  15. Is there any way to compare two structures automatically?
  16. Why we cannot use relational and logical operators in structure variable?
  17. 20 floats are to bestored in memory.What would you prefer,an array or a structure?
  18. state true or false for the following
    1. All structure elements are stored in contiguous memory locations
    2. In an array of structures,not only are all structures stored in contiguous memory locations,but the elements of individual structures arealso stored in contiguous locations.

    Tuesday, 11 May 2010

    Questions on Arrays

    1. Define Array?
    2. The starting location of an array is 1000.If the array[1..5/..4] is stored in a row major order form what is the location of element[4][3].Each element occupies 4 bytes.
    3. What is the size of the array declared as double *x[5]?
    4. Is the expressions arr and *arr are same for array of integers?
    5. Is it possible to allocate arrays dynamically?
    6. Difference between string and arrays?
    7. Difference between arrays and linked list?
    8. Does mentioning arrayname gives basse addressin all contexts?
    9. How can we increase the size of a dynamically allocated array?
    10. Is it possible to increase the size of statically allocated array?
    11. Difference between array and structure?
    12. How do you count just the number of elements in the array that are being used?
    13. Consider an array that can holds upto 100 elements, but only the first 20 elements are actually used.What are the values stored in the remaining elements?
    14. Write the logic for multiplying two 2 by 2 matrices and store the result in a third variable?
    15. How do you copy the elements of a 2 dimensional array in to a 1 dimensional array?
    16. Why array index is starting from zero? (or) Why arrays not store values from 1?
    17. How will you combine the elements of two integer arrays in to one single array in c language?
    18. How will you convert a 1 dimensional array in to a 2 dimensional array?
    19. How to split a string(using delimitor /) and store each portion to a separate array?
    20. What are the application of one dimensional and two dimensional arrays?
    21. Can we use heterogeneous declarations in arrays?If they are not declared what is the reason?
    22. What is the valid range of indexes for an array of 10 objects? What happens if we print the address of the 11th memory of that array?

    Monday, 10 May 2010

    Questions on Pointers

    1. What is pointer?
    2. What is NULL pointer?Is it same as uninitialized pointer?
    3. What does the error 'NULL Pointer Assignment' mean and what causes this error?
    4. Difference between NULL pointer and NULL macro?
    5. What is far pointer? Where we use it?http://www.blogger.com/post-edit.g?blogID=3012383994992801642&postID=2425531620599867473
    6. What are near,far and huge pointers? How many bytes are occupied by them?
    7. When you reallocate the memory which is currently referenced by several other pointers, do you have to readjust these other pointers or do they get readjusted automatically?
    8. Write down the equivalent pointer expression for referring the element a[i][j][k][l]?
    9. Advantages of using pointers in programs?
    10. Declare the following

      1. array of 3 pointers to chars
      2. array of 3 char pointers
      3. pointer to array of 3 chars
      4. pointer to function that receieves int pointer and returns float pointer
      5. pointer to function that receieves nothing and returns nothing
    11. How will you declare array of three function pointers where each function receives two ints and returns float?
    12. What is the size of pointer variable in C?How to calculate the size of pointer?
          size of pointer can be calculated by using sizeof() operator. Pointer stores the address of the variable. Address of variable is always an integer value. Storing integer value require 4bytes(32 bit compiler). So pointer variable require 4 bytes of memory
    13. What is the size of void pointer variable in c?
      void *ptr;
      sizeof(ptr)?
    14. What is the size of const pointer variable in C?
    15. Which pointer require more memory space int or character pointer?
          Size of pointer variable does not depends upon data type. Pointer variable only stores the address of the variable. Address is always integer value. So size of pointer variabl of any type is 4 bytes(32 bit compiler)
    16. Write the equivalent pointer expression for the following array variables?
      1. a[i][j]
      2. a[i][j][k]
      3. a[i][j][k][l]