Antoine Le baux Antoine Le baux - 1 year ago 66
C Question

Reversing a string on C

I'm new in in code and I'm doing K&R for C coding, but I have some simple questions that are complicating me, I know it can be a very stupid question but again, I'm new and if you can explain me in a way that a noob would understand I will appreciate it.

Just want to store "4321" in srev[] but it just doesn't print anything, I know there is other ways to reverse a string but I would like to know why this one doesn't work, thanks.

#include <stdio.h>

#define MAXL 1000

char s[MAXL] = "1234";
char srev[MAXL];


int i =0;
for(i=0; 4>=i; ++i){
srev[i] = s[4-i];

printf("srev[]: %s", srev);

Answer Source

In your for loop the last thing you do is put s[4] into srev[0]. The that element (the fifth because arrays are zero indexed) is the strings null terminator. That means that the first thing in srev tells printf to stop printing.
Change your loop to this:

for(i=0; 3>=i; ++i){  
    srev[i] = s[3-i];


for(i=0; 4 > i; ++i){  
    srev[i] = s[3-i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download