Pages

Wednesday, November 30, 2016

Test if a given number is power of two in one line in C

In binary representation, a number is power of two if it has only one on bit and others bits as off.
For ex: binary representation of 8 is 1000 (contains only one on bit) whereas, that of 5 is 0101(contains two on bits).

If a number is power of two, for example 8, bitwise and of 8 and 7 is 0

Code:

#include <stdio.h>

int main(){
     int n = 8;
     if((!(n & (n-1)))){  // & is bitwise and whereas ! is logical not
          printf("The number is power of two\n");
     }else{
           printf("Not a power of two\n");
     }
     return 0;
}

However, this does not give correct result for n = 0. For n = 0, the above expression would be 1, thus printing, "the number is power of two". To accommodate, the case for n = 0, use the following code.

 #include <stdio.h>

int main(){
     int n = 8;
     if((n && !(n & (n-1)))){     // && is logical and, ! is logical not and & is bitwise and
          printf("The number is power of two\n");
     }else{
           printf("Not a power of two\n");
     }
     return 0;
}


Wednesday, November 23, 2016

lvalue required as left operand of assignment error when using C

Consider the following array:

int arr[5] = {1,2,3,4,5};

We know that name of the array points to address of first element of array i.e. address of 1 here.

So, the following code:

printf("%u",arr);

will give address of 1 in this case. This address of 1 is constant and cannot be changed. So, in a C program, it is not possible to change the value of arr.

The following code will give an error: lvalue required as left operand

#include

int main(){
     int arr[5] = {1,2,3,4,5};  
     arr++;
     return 0;
}

Even if you give a lvalue by modifying the code as below, it will still throw a compilation error.
error: incompatible types when assigning to type 'int[5]' from type 'int *'  

int main(){
     int arr[5] = {1,2,3,4,5};  
     arr = arr +1;
     return 0;
}

Thus, important thing to understand here is, we are missing out on a key concept.
Here, arr is a constant just like a const variable which cannot be changed and any attempt to change that value will result in a compilation error.

It will be more comprehensible if the error "lvalue required as left operand" would have read "arr is a constant and cannot be changed".

Having said that, the following operation is valid.

int main(){
     int arr[5] = {1,2,3,4,5};  
     printf("%d\n", *(arr + 1));
     return 0;
}

This is because, we are fetching the value at index 1 of array arr and not increasing the value of arr.

This is similar to int y = x +5;
We are not increasing the value of x here. We are just adding 5 to value of 5 and assigning it to y.



Tuesday, November 22, 2016

Advantages of Pointers

Pointers are used frequently in C, as they offer a number of benefits to the programmers. They include the following:

1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers allow passing a function as argument to other functions.
4. The use of pointer arrays to character strings results in saving of data storage space in memory.
5. Pointers allow C to support dynamic memory management.
6. Pointers provide an efficient way for manipulating dynamic data structures such as structures,             linked lists, queues, stacks and trees.
7. Pointers increase the execution speed and thus reduce the program execution time.

Source : https://codingsec.net/2016/11/advantages-using-pointers-c-programming/

Fetching elements in multi-dimensional array in C using pointers

As opposed to traditional method of using integer indexes, elements in a multi-dimensional array in C can be fetched using pointers.

Consider the following code using multi-dimensional array.

#include <stdio.h>

int main()
{
 
    int matrix[10][20] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int i,j;
    for(i = 0; i < 3;i++){
        for(j = 0 ; j< 4 ;j++){
            printf("%d\n",(*(*(matrix +i)) + j));  
        }
    }
 
return 0;
}

Different methods are available to print individual elements from the above array. Three different approaches are described below.

1.  *(a[i] + j) :
    a[i] refers to first element in i th array of matrix. Adding j gives the address of j th element in i th array.
    De-referencing this address gives value at ith row and j th column of matrix array

2. (*(matrix + i))[j]
      *(matrix + i) gives address of first element of i th row of matrix. [j] gives j th column of row i.

3. *(*(matrix + i) + j)
     As above, *(matrix + i) gives address of first element of i th row of matrix. Adding j gives address of j th column of matrix. De-referencing this element gives the value of  i th row and j th column.