Antoine Le baux
Antoine Le baux

Reputation: 37

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]; 

main(){

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

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

Upvotes: 0

Views: 89

Answers (3)

jez
jez

Reputation: 15349

To expand upon the comment by Dunno: the string "1234"in C is five bytes long. The fifth byte s[4] is a zero byte denoting string termination.

Your code copies that zero byte to srev[0], so now you have a C string that terminates before it has even begun.

Use i<4 in your for loop (and adjust the arithmetic to 3-i accordingly) so that you only swap the non-zero bytes. Then set srev[4] = '\0'; explicitly to terminate the new string in the correct place.

Upvotes: 5

Raindrop7
Raindrop7

Reputation: 3911

becuase s[4] = '\0' which means end of character string. if you assign null terminator to a string it means you tell it: "it's the end, accept no more characters":

#include <stdio.h>

#define MAXL 1000

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

main(){

    int i = 0;                   
    for(i=0; 4 > i; ++i){  
        srev[i] = s[3-i];  // 3 - 0 = 3 so s[3] = '4' s4 = '\0'
    }

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

Upvotes: 0

Riley
Riley

Reputation: 698

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];
}

or:

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

Upvotes: 2

Related Questions