#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