使用递归函数的字符串反向程序 [英] string reverse program using recursive function
本文介绍了使用递归函数的字符串反向程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此程序中,我没有得到输出,也没有发现我的错误,只有指出我的错误并仅给我提示,那里的任何其他方法仅给我提示. ..
In this program i did''t get output i did''t find out my mistake any one point-out my mistake and give me a hint only and any other method ''s there give the hint to me only...
#include<stdio.h>
#include<conio.h>
void fun(char *s, int l1);
void main()
{
//void rev(char, int);
char str;
int l;
clrscr();
printf("Enter the string: ");
scanf("%s",&str);
printf("%s",str);
//s=&str;
l = strlen(str);
fun(&str,l);
getch();
}
void fun(char *s,int l1)
{
char *temp;
if(l1 == -1)
exit(0);
else
{
temp = s+(l1-1);
printf("%c",*temp);
l1-=1;
fun(s,l1);
}
}
推荐答案
立即跳出来的一件事是,您正在使用的不是您自己的内存!
也就是说,您的变量"str"是一个char-它仅保留1个字节的内存,但是在scanf语句中,您正在将未知数量的char读入您拥有的一个字节的内存中((未知)字符数-1)存储到随后的内存中.
您应该:
- 静态或动态分配一些内存
- 使用 ^ ],它允许您指定要复制的最大字符数
The thing that immediately leaps out at one is the fact that you''re using memory that isn''t yours!
That is to say, your variable ''str'' is a char - it holds just 1 byte of memory, yet in the scanf statement you''re reading an unknown number of chars into just one byte of memory you own and (unknown number of chars - 1) into memory that follows.
You should:
- Allocate some memory, either statically or dynamically
- use scanf_s[^], which allows you to specify the max # of chars copied
const int bufSize = 1024;
char str[bufSize]; // or some other arbitrary num long enough to hold string
或
const int bufSize = 1024;
char *str;
str = (char*)calloc(bufSize, 1); // see above note on length - alloc & clear mem
然后使用:
And then use:
scanf_s("%s", str, bufSize-1);
我没有看过程序的其余部分.这可能会或可能不会解决您的问题.无论如何,仍然是您应该解决的错误.
I haven''t looked at the rest of the program. This may or may not fix your problem. In any case, it''s still an error that you should fix.
这篇关于使用递归函数的字符串反向程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文