0

I have been working on this very simple question. I am trying to reverse a array of chars and then store this reversed array of chars into another array using c language. Here is my code, I can not figure out what is the problem of my code. I really do not understand why when I try to print out my stcp which is the array with the reversed string, there is nothing show up on the screen. Please advice, any help would be really appreciate.

#include<stdio.h>

int main() {
    char st[100];
    scanf("%s", st);
    int count = 0;
    while(st[count] != '\0'){
        count++;
    }

    //printf("%s", st);
    char stcp[100];
    int i, j = 0;
    for(i = count-1; i >= 0; i--){
        st[i] = stcp[j];
        j++;
    }

    puts(stcp);
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
perryfanfan
  • 161
  • 3
  • 10

2 Answers2

4

I think you mean the following

char stcp[100];
int i = count, j = 0;

while ( i != 0 ) stcp[j++] = st[--i];
stcp[j] = '\0';

As for your original code then you have to exchange operands in this statement

   st[i] = stcp[j];

and string stcp must be appended with the terminating zero.

Take into account that function main should be defined in C like

int main( void )

As for me I would declare variables count, i, and j as having type size_t.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You need to switch this line:

st[i] = stcp[j];

To this:

stcp[j] = st[i];