row248
row248

Reputation: 119

Print array which was filled in other funciton

I trying reverse my string and print that result.

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

void reverse(char *string, char *revstr)
{   
    int length, i, j;

    length = strlen(string);

    for (i=length, j=0; i >= 0; i--, j++) {
        revstr[j] = string[i];
    }
}

int void()
{   
    char string[] = "reverse!";
    int length = strlen(string);
    char revstr[length];
    int i;

    reverse(string, revstr);

    printf("%s", revstr); //nothing
    for (i=0; i<=strlen(string); i++) {
        printf("%c", revstr[i]); //It's work
    }
    printf("\n");

    return 0;
}

Upvotes: 0

Views: 78

Answers (1)

ouah
ouah

Reputation: 145899

From C definition a string is a contiguous sequence of characters terminated by and including the first null character. You should not reverse the trailing null terminator of the string.

Change:

for (i=length, j=0; i >= 0; i--, j++)

to this

for (i = length - 1, j=0; i >= 0; i--, j++) {

and manually add the trailing null terminator at the end of your reverse function:

revstr[length] = '\0';

You should also reserve enough room for the null terminator:

Change:

char revstr[length];

to this:

char revstr[length + 1];

Upvotes: 8

Related Questions