Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用指针的字符串反转_C_Arrays_Pointers_For Loop - Fatal编程技术网

C 使用指针的字符串反转

C 使用指针的字符串反转,c,arrays,pointers,for-loop,C,Arrays,Pointers,For Loop,问题-要使用指针反转字符串, 但是我的代码不是打印反向字符串,而是打印字符串的第一个字母 #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 s

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

#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))!='\0';sptr++,ptr--)
        {
            ;
        }
    printf("%s",a);
    return 0;

}
#包括
int main()
{
int i;
charn[100];
char*ptr;
ptr=n;
chara[100];
char*sptr;
sptr=a;
scanf(“%s”,n);
for(i=0;n[i]!=0;i++)//计算字符串的大小
对于(;(*sptr=*(ptr+i))!='\0';sptr++,ptr--)
{
;
}
printf(“%s”,a);
返回0;
}

您的问题有两方面

首先,您缺少一个
for
循环后的code>

for(i=0;n[i]!=0;i++); //note the ;
其次,您使用的数组索引超出范围

for(;(*sptr=*(ptr+i))!='\0';sptr++,ptr--)
在使用它之前,您需要减少
i
一次

你应该写

for(;(*sptr=*(ptr+i-1))!='\0';sptr++,ptr--)

注意:伊姆霍,你把一件简单的事情弄得太复杂了。想一个更简单的逻辑。有很多。例如,请点击WhozCraig先生评论中的链接。

“字符串反转”将在该网站上出现大量点击。并且不需要嵌套for循环,因此请重新考虑您的算法。因为您有一个嵌套循环,即内部
for
循环被嵌套在计算字符串长度的循环中,据说该循环用于执行反转。这是故意的吗?我真的没有得到你的程序不,它不是打算嵌套的,我的方法是使用它来计算字符串的长度。可能重复或,并忘记所有的索引。这就是指针的作用。