1

Does anybody know why the variable s2 does not get printed. This code works if I am not using declaring a function, but just put the whole code in main. However, it does not print anything if I try to declare as an int function or void function. I think it's something fundamental about strings that I do not understand.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int reverseOrderString()
{
    char s1[100];
    char s2[100];

    int counter, end, begin = 0;

    printf("Type in a string\n");
    gets(s1);

    while(s1[counter] != '\0')
    {
        counter++;
    }

    end = counter-1;

    for (begin = 0; begin < counter; begin++)
    {
        s2[begin] = s1[end];
        end--;
    }

    s2[begin] = '\0';

   return s2;


}


int main()
{

    printf("%s", reverseOrderString());

    return 0;
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Tungstein
  • 31
  • 5

1 Answers1

1

Multiple issues with code:

  1. Uninitialized variables
  2. Returning a local array which after function returns is not valid memory
  3. Change to fgets

#include <stdio.h>
#include <string.h>

void reverseOrderString(char *s)
{
    char s2[100];

    int counter=0, end=99, begin = 0;

    printf("Type in a string\n");
    fgets (s2, 100, stdin);

    while(s2[counter] != '\0')
    {
        counter++;
    }

    end = counter-1;

    for (begin = 0; begin < counter; begin++)
    {
        s[begin] = s2[end-1];
        end--;
    }

    s2[begin] = '\0';
    return;
}

int main()
{
    char str[100];
    reverseOrderString(str);
    printf("%s\n", str);
    return 0;
}

Input:

Reverse me!!

Output:

!!em esreveR
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • Damn, I have no clue why I had declared the function to an int. I did not even think about that s1 was a local variable, and not a global variable. Also now I learned that gets is a bad function to use. I learned a lot from your feedback, I appreciate it. Thanks. – Tungstein May 24 '20 at 12:59