倒车的话。 (null终止c string char数组)。为什么它不起作用

时间:2015-05-19 00:12:43

标签: c c-strings

我正在尝试反转char数组并使用%s打印它。但它不起作用。我没有打印任何东西。这是为什么?我的代码非常简单/

char* reverse(char* word){

        int i = 0;

        int length=0;


    while (word[i] != '\0'){
                i++;

           }

          length = i;

          char* temp_word = malloc(length* sizeof(char));

        for (i = 0; i < length; i++){

            temp_word[i] = word[length - i];

            word[i] = temp_word[i];

        }


        return word ;

    }

2 个答案:

答案 0 :(得分:1)

temp_word[i] = word[length - i];

应该是

temp_word[i] = word[length - i - 1];

如果word[]长度为3个字符,则word[3]实际上是空终止符。

答案 1 :(得分:1)

这有效......你没有为Null终结符分配空间......而你正在通过这样做来'覆盖'word [i] = temp_word [i]'...

#include <stdio.h>
#include <stdlib.h>


char *reverse(char *);


int main()
{
        char sWord[10] = "PHONE";
        char *temp = NULL;

        printf("Before reverse() => %s\n", sWord);

        temp = reverse(sWord);

        printf("After reverse() => %s\n", temp);

        return 0;
}


char *reverse(char *word)
{
        int i = 0;
        int length = 0;

        while(word[i] != '\0')
        {
                i++;
        }

        length = i;

        char *temp_word = malloc(length * (sizeof(char)+1)); // +1 here.

        for (i = 0; i < length; i++)
        {
                temp_word[i] = word[length - (i+1)];
                //word[i] = temp_word[i]; <== Do not need this.
        }

        temp_word[length] = '\0';

        return temp_word ;
}