My C program isn't reaching the "return 0;" statement:
The program is supposed to invert a string by creating a new string and there putting the contents of the original string in reverse order. The problem is, it isn't reaching the "return 0;" statement. I even added the statement
inside the invertString function to check whether a memory error is occurring, but it isn't executing. What is possibly going on? Thanks in advance.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *invertString( const char *const str );
int main( void )
{
char string[ 25 ];
char *ptr;
printf( "Enter a string without whitespace: " );
scanf( "%25s", string );
ptr = invertString( string );
if ( ptr != NULL )
{
printf( "The inverted string is %s.\n", ptr );
}
else
{
printf( "A memory error occurred.\n" );
}
printf( "LINE %d.\n", __LINE__ );
return 0;
}
char *invertString( const char *const str )
{
unsigned int i;
unsigned int j;
unsigned int lengthOfStr = strlen( str );
char *newStr = ( char * )malloc( ( lengthOfStr + 1 ) * sizeof( char ) );
if ( newStr == NULL )
{
printf( "ERROR!" );
return newStr;
}
for ( i = lengthOfStr - 1, j = 0 ; i >= 0 ; --i, ++j )
{
*( newStr + j ) = *( str + i );
}
*( newStr + j ) = '\0';
return newStr;
}
Code:
printf( "ERROR!" );
Comment