计划扭转一个字符串 [英] program to reverse a string

查看:90
本文介绍了计划扭转一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C.初学者,我试图此程序反转字符串。任何帮助什么错呢?

 #包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;字符*反向(字符*);无效的主要()
{
    烧焦海峡[] =kundan;
    INT LEN = strlen的(STR);
    字符* PTR;
    PTR =反转(STR);
    的printf(反向字符串是:%S,PTR);
}字符*反转(STR)
{
    字符* RTR = str中;
    焦炭QTR [10];    的for(int i = LEN-1; I< = 0;我 - )
    {
        QTR = RTR + I;
        QTR ++;
    }
    返回QTR;
}


解决方案

您不尊重变量范围。这一个有用的参考,这里

例如,在反向(),你指的 LEN 循环。然而, LEN 定义主,因此不能用于反向() 。的(难道这甚至编译?)

您从反向返回的值()是一个指针,是只在该函数范围堆栈值。当调用函数,的main(),将结束与一个有效的指针,该指针是指已经跌出范围的信息时,反向()返回,因此是的挥发性的,可能会改变。对于这个简单的例子,你可以通过值而不是通过引用返回的字符串逆转。 (发送回的字符,而不是一个指向他们的阵列。)

I am a beginner in C. I was trying this program to reverse a string. Any help whats wrong with it?

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

char *reverse(char *);

void main()
{
    char str[]="kundan";
    int len=strlen(str);
    char *ptr;
    ptr=reverse(str);
    printf("the reversed string is :%s",ptr);
}

char *reverse(str)
{
    char *rtr=str;
    char qtr[10];

    for(int i=len-1;i<=0;i--)
    {
        qtr=rtr+i;
        qtr++;
    }
    return qtr;
}

解决方案

You aren't respecting variable scope. One useful reference about this, here.

For example, in reverse(), you refer to len in the for loop. However, len is defined in main, and therefore isn't available to reverse(). (Does this even compile?)

The value you're returning from reverse() is a pointer to a stack value that is only in scope in that function. While the calling function, main(), will end up with a valid pointer, the information that the pointer is referring to has dropped out of scope when reverse() returned, and is therefore volatile, subject to change. For this simple example, you could return the reversed string by value, rather than by reference. (Send back the array of characters, not a pointer to them.)

这篇关于计划扭转一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆