【发布时间】:2020-04-28 16:09:05
【问题描述】:
我这里有这段代码。我正在尝试实施,但我遇到了错误,我不知道如何摆脱它。这是一个堆栈。我必须调用该函数以在其中插入值,但编译器一直显示此错误并且不让我做任何其他事情。
Passing 'pilha' to parameter of incompatible type 'int'
pilha * cria_pilha(){
pilha *pi;
pi = malloc(sizeof(pilha));
if (!pi) {
pi -> topo = 0;
}
return pi;
}
我正在尝试在这里调用它。
int main (int argc, const char * argv[]){
//Cria vetor de struct preenchido com a quantidade MAX_ELEMENTOS
pilha * pi = cria_pilha();
pilha p[MAX_ELEMENTOS] = {1, 2, 3, 4, 5,
6, 7, 8, 9, 10};
//Call the function Stack, then pass by argument p[]
//stacking the values MAX_ELEMENTS times.
for (int i = 0; i < MAX_ELEMENTOS; i++) {
//The error happens here. I already identified the cause but
//I've got no idea how to solve it. Any help please?
empilha(pi, p[i]); -- Passing 'pilha' to parameter of incompatible type 'int'
}
for (int i = 0; i < MAX_ELEMENTOS; i++) {
desempilha(pi);
}
}
我正在调用函数int empilha(pilha *pi, int p);,据我了解,该函数具有与 int 类型不兼容的 pilha *pi。我该如何解决这个问题?
这是我的全部代码。
#include <stdio.h>
#include <stdlib.h>
#define MAX_ELEMENTOS 10
typedef struct {
int elementos[MAX_ELEMENTOS];
int topo;
} pilha;
pilha * cria_pilha(){
pilha *pi;
pi = malloc(sizeof(pilha));
if (!pi) {
pi -> topo = 0;
}
return pi;
}
int empilha(pilha *pi, int p);
int desempilha(pilha *pi);
int tamanho (pilha *pi);
void destroi(pilha *pi);
int main (int argc, const char * argv[]){
//Cria vetor de struct preenchido com a quantidade MAX_ELEMENTOS
pilha * pi = cria_pilha();
pilha p[MAX_ELEMENTOS] = {1, 2, 3, 4, 5,
6, 7, 8, 9, 10};
//Chama função empilhar, passa por argumento o velho p[]
//para função empilha MAX_ELEMENTOS vezes.
for (int i = 0; i < MAX_ELEMENTOS; i++) {
empilha(pi, p[i]);
}
for (int i = 0; i < MAX_ELEMENTOS; i++) {
desempilha(pi);
}
}
int empilha(pilha *pi, int p){
if (pi == NULL || pi -> elementos == ((int*)MAX_ELEMENTOS)) {
printf("Erro, pilha cheia.\n");
return 0;
}
pi -> elementos[pi->topo] = p;
pi -> topo = pi -> topo + 1;
return 1;
}
int desempilha(pilha *pi){
if (pi == NULL || pi -> elementos[0] == 0) {
return 0;
}
pi -> topo = pi -> topo -1;
return pi -> elementos[pi->topo];
}
int tamanho(pilha *pi){
return pi -> topo;
}
void destroi(pilha *pi){
free(pi);
}
【问题讨论】:
-
你不应该这样做
if (!pi) { pi -> topo = 0; },因为你会取消引用一个空指针。
标签: c data-structures stack