Write a program that displays the characters of its command line arguments in reverse order. (if the command line arguments are "one" and "two", the program should display "owt eno"
My program works. However, after giving the result it crashes ("the program has stopped working").
#include <stdio.h>
#include <string.h>
char * myReverse ( char * string );
int main ( int argc, char *argcv[] )
{
char args[argc-2];
int i = argc - 1;
while ( i > 0 )
{
char * rev = myReverse (argcv[i--]);
puts(rev);
}
return 0;
}
char * myReverse ( char * string )
{
int i = strlen(string) - 1 ;
char * revString;
int pos = 0;
revString[i+1] = '\0';
while ( i >= 0 )
{
revString[i] = string[pos++];
i--;
}
return revString;
}
You forget to allocated memory for your strings. You can solve this by using stack allocated arrays or by allocating memory on the heap. I solved the issue by allocating memory on the heap by calling malloc
.
Update: pointer checked against null
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // This changed
char * myReverse ( char * string );
int main ( int argc, char *argcv[] )
{
char args[argc-2];
int i = argc - 1;
while ( i > 0 )
{
char * rev = myReverse (argcv[i--]);
if(ptr != NULL) {
puts(rev);
free(rev); // This changed
}
}
return 0;
}
char * myReverse ( char * string )
{
int i = strlen(string) - 1 ;
char * revString = malloc(i + 1); // This changed
if(ptr == NULL) return NULL;
int pos = 0;
revString[i+1] = '\0';
while ( i >= 0 )
{
revString[i] = string[pos++];
i--;
}
return revString;
}