#include<stdio.h>
#include<stdlib.h>
#define n ((sizeof(char)) * 100)
int stringlength(char * str)
{
int count=0;
while(*str)
{
if(*str == '\n')
{
*str=0;
}
else
count++, str++;
}
return count;
}
int palin1(char *str, int k)
{
char * pend = str + k - 1;
if(*pend != *str)
return 0;
else
palin1(str+1, k-1);
return 1;
}
int palin(char *str)
{
int length = stringlength(str), f=0;
char *pend = str + length - 1;
while(str <= pend)
{
if(*str == *pend) f=1;
else
return (f = 0);
str++, pend--;
}
return 1;
}
main()
{
char * ps = (char *)malloc(n);
int flag;
if(ps == NULL) printf("Malloc Fail\n");
else
{
printf("Malloc Succeeded, you have memory of %d bytes\n", n);
printf("This program checks if String is Palindrome or not\n\
\nEnter your String: ");
fgets(ps, 100, stdin);
printf("You entered: %s of length %d", ps, stringlength(ps));
int i = 0;
printf("\n\nEnter:\n1.Using iteration\n2.Using Recursion ");
scanf("%d", &i);
switch(i)
{
case 1:
flag=palin(ps);
break;
case 2:
flag=palin1(ps,stringlength(ps));
break;
default:
printf("Invalid input");
}
if(flag) printf("\nYou entered a Palindrome");
else printf("\nNot a Palindrome");
}
free (ps);
return 0;
}
为什么上面的程序http://www.ideone.com/qpGxi不给上把输入的任何输出:程序异常终止,如果输入是非常大的
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
我知道fgets(ps,100,stdin)
将只需要100字符而不是更多,但为什么程序停止执行?
这只是真棒: - ))#define n((sizeof(char))* 100)' – cnicutar
哈哈,是的,这是非常不必要的。我从来没有见过(sizeof(char))不等于1的系统。 – Chriszuma
@Lohit:我建议你不要定义小写字母标识符。我曾经用一个'#define'来调试学员代码,当他引入一个名称相同的变量时,开始无法编译......花了我很多时间来找到它! – pmg