字符串反向-segfault

问题描述 投票:-1回答:1

这不是重复的qn。一种新的方法用于从已询问的qn中反转字符串。

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

char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    char *retStr;

    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }

    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}

int main()
{
    char *str = NULL, *revStr2 = NULL;
    str = (char *) malloc (5);
    strcpy(str, "hello");
    printf("\n%s\n", str);
    printf("\n%s\n", revStr(str));
}

给我输出为O / P:


hello
first h for 0
first e for 1
first l for 2
first l for 3
first o for 4
thrd h for 4
thrd e for 3
thrd l for 2
thrd l for 1
thrd o for 0
olleh

Segmentation fault


有人可以帮助使用此方法如何实现字符串恢复。谢谢,Preethi

c string reverse
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.