计划扭转一个字符串 [英] program to reverse a string
问题描述
我在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屋!