C program to reverse a string

Graphic showing typeset

This is a very simple C program to reverse all the characters in a given string. As for example considering the string “hello world”, the program should output “dlrow olleh”. The string reversal problem is a common embedded software interview question asked for both entry level and middle level firmware engineering positions.

Code walk-through

This simple C program is to reverse a string. Reversing a string is a classic interview question which is asked commonly. In this given example, the function strRev() reverses the characters present in the character array.

The character pointers begin and end are assigned with the address of the received string str.

The lines,

checks for a null pointer or for a null value and jumps to error: label.

A character pointer end is moved to the last character (excluding the null character) in the received string in the following lines,

Finally the begin and end pointers’ dereferenced characters are swapped until all characters are swapped.

Now the string characters are reversed and the new string is printed from main().

Leave a Reply 0

Your email address will not be published. Required fields are marked *