使用指针的字符串反转

String Reversal using pointers

问题-要使用指针反转字符串, 但是我的代码不是打印反转字符串,而是打印字符串的第一个字母。

#include<stdio.h>

int main()
{
    int i;
    char n[100];
    char *ptr;
    ptr = n;
    char a[100];
    char *sptr;
    sptr = a;
    scanf("%s", n);

    for(i=0;n[i]!=0;i++)//Calculating the size of the string
        for(;(*sptr=*(ptr+i))!='[=10=]';sptr++,ptr--)
        {
            ;
        }
    printf("%s",a);
    return 0;

}

你的问题是双重的。

首先,您在第一个 for 循环之后缺少 ;

for(i=0;n[i]!=0;i++); //note the ;

其次,你使用的数组索引越界

for(;(*sptr=*(ptr+i))!='[=11=]';sptr++,ptr--)

使用前需要减少i一次

你应该写

for(;(*sptr=*(ptr+i-1))!='[=12=]';sptr++,ptr--)

注意:恕我直言,您把简单的事情搞得太复杂了。想一个更简单的逻辑。有许多。对于 live 示例,请遵循 WhozCraig 先生评论中的 link。