slee0743
slee0743

Reputation: 17

reversing a string in C

#include <stdio.h>
void reverse(int len, char s[], char b[]);

int main() {
    char s[5] = "hello";
    char b[5];
    reverse(5, s, b);
    return 0;
}

void reverse(int len, char s[], char b[]) {
    int i;
    for (i = 0; i < len; i++) {
        b[(len - 1) - i] = s[i];
    }
    printf("%s : %s\n", s, b);
    printf("%s", b);
}

Here is my code above in C. When I run it, it switches the string s[] to b[] but b[]also includes s[]. Can someone please thoroughly explain what I'm doing wrong? I really appreciate it.

Upvotes: 1

Views: 177

Answers (5)

saruftw
saruftw

Reputation: 1164

In C, you just need to include

#include<string.h>

and use

strrev(a);

where a is the character array or string.

Whereas, your code can be modified too, to be written like this

#include <stdio.h>
void reverse(int len, char s[], char b[]);

int main() {
    char s[5] = "hello";
    char b[5];
    reverse(5, s, b);
    return 0;
}

void reverse(int len, char s[], char b[]) {
    int i,j;
    for (i = 0,j=len-1; i <=j; i++, j--) {
        b[j]=a[i];
    }
    printf("%s : %s\n", s, b);
    printf("%s", b);
}

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41017

char s[5] = "hello";

This is wrong, you need one more [6] in order to store the trailing '\0' (same for b)

It's better to omit the array size:

char s[] = "hello";
char b[sizeof(s)];

And you need b[i] = '\0'; after the for loop.

Upvotes: 8

Kailash Karki
Kailash Karki

Reputation: 2286

every string in c is terminated by \0 which is a null character. so the array size should be enough to hold the string along with null character. I will suggests to increase the size of array.

important :- 

at the last assign b[last_index]='\0'; so that string b can be terminated by \0. otherwise it might give garbage values along with actual data while printing the string b.

Upvotes: 0

unwind
unwind

Reputation: 399773

Your string buffers are too small, they must be six characters or more to hold the string "hello". Remember that strings C have a terminating '\0'-character at the end; that won't fit with space for only five characters.

Also, when reversing you never copy the terminating character.

You need b[len - 1] = '\0'; before exiting reverse().

When you pass non-terminated strings to printf()'s "%s" format, you get undefined behavior. Typically it "runs off the end" of the string, printing whatever it happens to find in memory, until it finds a character with the value 0 which causes it to stop.

Upvotes: 3

gnasher729
gnasher729

Reputation: 52538

The %s format specifier expects a string: An array of characters ending in a nul byte. You are not supplying that, so you are getting rubbish results. To hold a string with five characters, you need at least six chars.

Upvotes: 0

Related Questions