问题
Stack create(int c)
{
Stack S=(Stack)malloc(sizeof(struct stack));
S->size=c;
S->top=-1;
S->array=(char *)malloc(sizeof(char)*c);
return S;
}
Stack makeEmpty(void)
{
Stack *S1=create(100);
S1[0]->top=-1;
return S1;
}
char pop(Stack S)
{
return S->array[S->top--];
};
int main(void)
{
Stack *S1;
S1=makeEmpty();
int j;
int k=0;
char result[30];
for(j=0; j<2; j++)
{
char result1=pop(S1);
strcat(result, result1);
k++;
}
}
I skipped some parts, like typedef struct stack Stack
;
What I wanted to do was pop out elements from the stack while for-loop works. Then, store those elements in a new array which is result
. To check whether it works or not, I printed out but I had a runtime error. How to store the element and how to print it out?
回答1:
I've made copy&paste of your code, and it doesn't get compiled. I think that you are either not posting your actually code nor you don't bother to compile and read the compiler warnings. It's rather difficult to help you. Here some things I noticed:
1.
create
must return a pointer to Stack
, not the object.
Stack *create(int c)
{
Stack *S = malloc(sizeof *S);
S->size=c;
S->top=-1;
S->array = malloc(c);
return S;
}
2.
Same goes for makeEmpty
Stack *makeEmpty(void)
{
Stack *S1=create(100);
S1->top=-1;
return S1;
}
3.
pop
should get a pointer to Stack
, not the object
char pop(Stack *S)
{
return S->array[S->top--];
};
Here you should check whether there are elements on your stack. int pop(Stack *S, char *val)
where it returns 1 and writes on *val
on
success, and returns 0 otherwise would be better.
4.
Judging from your pop
you are pushing char
only. I don't get what you
are trying to do with strcat
. Either way, you are doing strcat
wrong. You
are declaring a stack with 100 spaces, but you are only declaring 30 spaces
for result
. What if you have more than 31 elements on your stack? I know
that you are only inspecting 2 elements but it's easy to overlook that and
expand it to go through all the stack without changing the memory requirements
for result
.
Also strcat
is a function that works with C-Strings, that means it expects
C-Strings. A C-String must be \0
terminated, yours are not. You have
something that looks like a C-String but it's not. If you insist on using
strcat
, the you should do it like this:
for(j=0; j<2; j++)
{
char result1[] = { pop(S1), 0 };
strcat(result, result1);
}
来源:https://stackoverflow.com/questions/48069933/c-character-push-and-pop-operation