在這裏,我正在檢查一個句子,檢查它是否是迴文。我是在學習堆棧的過程中這樣做的。在c中使用指針進行字符串操作
有沒有辦法我可以使用指針而不是字符數組'發送',以便在下面的代碼中輸入字符的數量不需要限制爲20? 代碼工作正常,但是應該在性能或其他方面有所改進嗎? 有什麼重要的指針,我應該記得使用堆棧,如初始化爲NULL? 感謝
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node
{
char data;
struct node *link;
}StackNode;
void insertData(StackNode **);
void push(StackNode **, char);
void checkData(StackNode **);
bool pop(StackNode **,char *);
char sent[20] = "";
void main()
{
StackNode *stackTop;
stackTop = NULL;
insertData(&stackTop);
checkData(&stackTop);
printf("\n");
return;
}
void insertData(StackNode **stackTop)
{
char c;
int len;
printf("Enter the Sentence\n");
while(((c = getchar()) != '\n'))
{
if(((c>='a' &&c<='z') || (c>='A' && c<='Z')))
{
if((c>='A' && c<='Z'))
{
int rem;
rem = c-'A';
c='a' + rem;
}
push(stackTop,c);
len = strlen(sent);
sent[len++]=c;
sent[len]='\0';
}
}
printf("Letters are %s\n\n",sent);
}
void push(StackNode **stackTop,char c)
{
StackNode *pNew;
pNew = (StackNode*) malloc(sizeof(StackNode));
if(!pNew)
{
printf("Error 100:Out of memory\n");
exit(100);
}
pNew->data = c;
pNew->link = *stackTop;
*stackTop = pNew;
}
void checkData(StackNode **stackTop)
{
char c;
int i=0;
while(pop(stackTop,&c))
{
if(c !=sent[i++])
{
printf("Not palindrome");
return;
}
}
printf("Palindrome");
}
bool pop(StackNode **stackTop,char *c)
{
StackNode *pNew;
pNew = *stackTop;
if(pNew == NULL)
return false;
*c = pNew->data;
*stackTop = pNew->link;
printf("char poped %c\n",*c);
free(pNew);
return true;
}
代碼中的任何地方都沒有字符數組,我也沒有看到任何20個字符的限制。這個問題似乎與代碼沒有任何關係。 – interjay
你的問題似乎並不符合你的代碼,但你總是可以使用指針而不是數組。 – mah
對不起,請現在檢查 – IRock