Wednesday, July 29, 2015

void* universal pointer

void* also known as universal pointer or generic pointer can be used to hold the address of any type assigned to it.

void* universal pointer can also be used as a function argument.

Below example transferValues function declares two void* arguments.

Instead of writing two different functions for int and double types only one transferValues function with void* arguments can be used.

void* seems to be usable but there are type-safety related problems with void pointer.

With a suitable casting operation existing void* universal pointer can be converted to an appropriate type.

Because a void pointer can not be dereferenced directly, static_cast can be used to cast from void* to another type.

Following error message is generated by the compiler if a void* is dereferenced before casting to an appropriate type.

'void*' is not a pointer-to-object type
           

Example void pointer project compiled with : g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2


#include <iostream>
using namespace std;

enum ParamType
{
    intType,
    doubleType
};

void transferValues( void* from, void* to, int size, ParamType pType)
{

    if( pType == intType )
    {
         for (int i= 0; i<size; i++)
         {
             static_cast<int*>(to)[i] = static_cast<int*>(from)[i];
         }
    }
    else if( pType == doubleType )
    {
         for (int i= 0; i<size; i++)
         {
             static_cast<double*>(to)[i] = static_cast<double*>(from)[i];
         }
    }
}

int main()
{

    int val = 5;
    void* vPtr = &val;
    // below line generates compile error
    // cout << *vPtr;
    int* newVal = static_cast<int*>(vPtr);
    cout << *newVal << endl;

    double dVal = 5.2;
    vPtr = &dVal;
    double* newDVal = static_cast<double*>(vPtr);
    cout << *newDVal << endl;

    char cVal = 'c';
    vPtr = &cVal;
    char* newCVal = static_cast<char*>(vPtr);
    cout << *newCVal;

    cout << endl << endl;

    int a[5] = { 1, 2, 1, 1, 1 };
    int b[5];

    cout << "Elements of array a = ";
    for( int i = 0; i<5; i++ )
        cout << a[i] << " ";

    cout << endl << "Elements of array b before casting = ";
    for( int i = 0; i<5; i++ )
        cout << b[i] << " ";

    transferValues( a, b, 5, intType );
    cout << endl << "Elements of array b after casting = ";
    for( int i = 0; i<5; i++ )
        cout <<  b[i] << " ";

    double c[5] = { 2.3, 3.3, 4.3, 5.3, 6.3 };
    double d[5];

    cout << endl << endl << "Elements of array c = ";
    for( int i = 0; i<5; i++ )
        cout << c[i] << " ";

    cout << endl <<"Elements of array d before casting = ";
    for( int i = 0; i<5; i++ )
        cout << d[i] << " ";

    transferValues( c, d, 5, doubleType );
    cout << endl << "Elements of array d after casting = ";
    for( int i = 0; i<5; i++ )
        cout << d[i] << " ";

    cout << endl << endl;

    return 0;
}

After running the program following terminal output displayed.


Saturday, July 25, 2015

toLower and toUpper Character Functions in C++ without using string.h and ctype.h

string.h and ctype.h libraries have got functions defined for converting characters from upper case to lower case and vice versa.

Sample functions below achieves in a c program following requirements :

1- convert a given character from lower case to upper case character
2- convert a given character from upper case to lower case character
3- convert a given whole string from lower case to upper case string
4- convert a given whole string from upper case to lower case string

with the following constraints :

1- All letters are English alphabet letters
2- There is no space in the input
3- Only character input is assumed


Main rule to remember when converting case for letters is :

Upper case character = Lower case character - ('a'-'A');
Lower case character = Upper case character + ('a'-'A');

Here the difference ('a'-'A') corresponds to 32.


#include <stdio.h>

char charToLower(const char& cUpper)
{
    if(cUpper>='A' && cUpper<='Z')
        return cUpper+('a'-'A');
    else
        return cUpper;
}

char charToUpper(const char& cLower)
{
    if(cLower>='a' && cLower<='z')
        return cLower-('a'-'A');
    else
        return cLower;
}

char* strToLower( char strUpper[] )
{
    int i = 0;
    while(strUpper[i] != '\0')
        i++;

    char* strLower = new char[i];
    i=0;
    while( strUpper[i] != '\0' )
    {
        if(strUpper[i]>='A' && strUpper[i]<='Z')
            strLower[i] = strUpper[i]+('a'-'A');
        i++;
    }
    return strLower;
}

char* strToUpper( char strLower[] )
{
    int i=0;
    while(strLower[i] != '\0')
        i++;

    char* strUpper = new char[i];
    i=0;
    while( strLower[i] != '\0' )
    {
        if( strLower[i]>='a' && strLower[i]<='z')
            strUpper[i] = strLower[i]-('a'-'A');
        i++;
    }
    return strUpper;
}

int main()
{
    char upperCaseChar = 'C';
    char lowerCaseChar = charToLower(upperCaseChar);
    printf("Upper Case Character : %c \n", upperCaseChar);
    printf("Lower Case Character : %c \n\n", lowerCaseChar);

    char lowerTestChar = 'f';
    char upperTestChar = charToUpper(lowerTestChar);
    printf("Lower Case Character : %c \n", lowerTestChar);
    printf("Upper Case Character : %c \n\n", upperTestChar);

    char upperCaseString[] = "TRKSH";
    char* lowerCaseString = strToLower(upperCaseString);
    printf("Upper Case String : %s \n", upperCaseString);
    printf("Lower Case String : %s \n\n", lowerCaseString);
    delete[] lowerCaseString;

    char lowerCaseTestString[] = "trksh";
    char* upperCaseTestString = strToUpper(lowerCaseTestString);
    printf("Lower Case String : %s \n", lowerCaseTestString);
    printf("Upper Case String : %s \n\n", upperCaseTestString);
    delete[] upperCaseTestString;

    return 0;
}

After running the program following terminal output displayed.


Friday, July 24, 2015

Palindrome String Check in C++ without using string.h

Palindrome check for a given string is very popular starting exercise for new programmers. It has got many implementations in Java and C++. Most of the implementations use existing String class in Java or string.h header in C++.

Following string palindrome check function in c++ without using string.h works with the constraints :

- strings that do not contain any space
- strings just contain English alphabet characters
- strings with more than 3 characters


#include <stdio.h>

int isPalindrome( const char* arr )
{
    int stringLength = 0;
    int index = 0;
    while(arr[index]!='\0')
    {
        ++stringLength;
        ++index;
    }

    if( stringLength >= 0 && stringLength <=2 )
        return 0;

    for(int i = 0; i<stringLength/2; i++)
    {
        if(arr[i] != arr[stringLength-1-i])
            return 0;
    }

    return 1;
}

int main()
{
    const char* stringToCheck1 = "aba";
    int res = isPalindrome(stringToCheck1);
    if(res)
        printf("%s is palindrome\n", stringToCheck1);
    else
        printf("%s is not palindrome\n",stringToCheck1);

    const char* stringToCheck2 = "abba";
    res = isPalindrome(stringToCheck2);
    if(res)
        printf("%s is palindrome\n",stringToCheck2);
    else
        printf("%s is not palindrome\n",stringToCheck2);

    const char* stringToCheck3 = "abccccba";
    res = isPalindrome(stringToCheck3);
    if(res)
        printf("%s is palindrome\n",stringToCheck3);
    else
        printf("%s is not palindrome\n",stringToCheck3);

    const char* stringToCheck4 = "abcc111211ccba";
    res = isPalindrome(stringToCheck4);
    if(res)
        printf("%s is palindrome\n",stringToCheck4);
    else
        printf("%s is not palindrome\n",stringToCheck4);

    const char* stringToCheck5 = "";
    res = isPalindrome(stringToCheck5);
    if(res)
        printf("%s is palindrome\n",stringToCheck5);
    else
        printf("%s is not palindrome\n",stringToCheck5);

    return 0;
}

After executing above main function following terminal output is produced.