/* Pgm to print string from commandline and reverse it */
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
int main(int argc, char *argv[]) {
if(argc<1){
perror("Not enough arguments");
}
// Printing the string
for(int i=1; i<argc ; i++){
printf("%s\n",argv[i]);
}
//Part to print the string in reverse
char *arr = (char*) malloc(sizeof(argv[1])+1); // +1 for the NULL terminator
strcpy(arr,argv[1]);
char *str = (char*) malloc(sizeof(argv[1])+1); //buffer array
//Reverse part begins
int j=0;
for(int i= sizeof(argv[1]); i>=0 ; i--){
str[j] = arr[i];
j++;
}
for(int j=0;j<sizeof(argv[1]);j++){ // Printing the reverse string
printf("R=%s\n",&str[j]);
}
free(arr);
free(str);
return 0;
}
This program is expected to print the text from argv[1] on commandline in reverse order. But the output I get is weird. output
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ gcc linex.c -o linex -Wall -pedantic -std=c99
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex hello
hello
R=
R=
R=
R=
R=olleh
R=lleh
R=leh
R=eh
Also when the input is above a certain number of characters, it automatically truncates it:
user@DESKTOP-KI53T6C:/mnt/c/Users/user/Documents/C programs$ ./linex strcmpppssdsdssdsd
strcmpppssdsdssdsd
R=spppmcrts
R=pppmcrts
R=ppmcrts
R=pmcrts
R=mcrts
R=crts
R=rts
R=ts
All I want is the output to be : 'olleh' when I type 'hello'