The issue that prevents the code from working is the missmatch in the size of o and c containers, and the read size in fgets, since fgets null-terminates the string read from input.
So let's say n = 6 as you read your string, fgets replaces the 6th character with a null-terminator, when you reverse it the null-terminator will now be the first character in o, essentially, it will be an empty string, as a string is a null-terminated char-array, or byte-array.
To fix this give fgets the size of your mallocced space.
fgets(c, n + 1, stdin);
And null-terminate o when you are finished reversing.
*(o + n) = '\0';
Or
o[n] = '\0'; //you can use this notation which is more readable than dereferencing
Minor issues:
- The fact that you switch the names of main arguments. It normally is
int main(int argc, char * argv[]). That can be confusing for someone who reads your code.
char *c = malloc((sizeof(char) * n) + 1); has unnecessary logic, it can be char *c = malloc(n + 1);, a char is one byte in size.
- There is an underlying problem with the logic of the program, when the inputed string is shorter than what you ask the user the outupt will not be the desired one, you can make an extra effort bullet-proofing your code for erroneous inputs.
All things considered, taking your code as base, it can be something like:
//Only the changed parts are represented, the rest is the same
#include <string.h> //for strlen
//...
if (argc != 2 || atoi(argv[1]) < 1) { //n must be positive (I switched argv and argc)
printf("Please enter the number of elements in your string!\n");
return 1;
}
size_t n = atoi(argv[1]); //size_t type more suited for sizes
char *c = malloc(n + 1);
char *o = malloc(n + 1);
//...
fgets(c, n + 1, stdin); //as stated n + 1 size argument
if(strlen(c) < n) { //if the length of inputed string is shorter than intended
puts("The string size shorter than stated!");
return 1;
}
//...
for (size_t i = 0; i < n + 1; i++) { //repalced int iterator type whith size_t
//...
o[n] = '\0'; //null terminate o
//...
c[n - 1]is zero, makingoan empty string"\0......"?fgets(c, n, stdin);->fgets(c, n+1, stdin);1to mallocnto be the number of characters in the string.argvandargc??? Strong suggestion to OP... keep usingint main(int argc, char **argv)... don't swap main argument standard identifiers.