我有几年的 java 经验,但我对 C 很陌生。我仍在努力弄清楚何时以及何时不使用指针。我得到了这个基本代码,需要完成“push”方法,以便将下一个元素插入堆栈,但我收到错误消息:
请求非结构中的成员“top”。
#include <assert.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
int exit_status = EXIT_SUCCESS;
#define EMPTY (-1)
#define SIZE 16
typedef struct stack stack;
struct stack {
int top;
double numbers[SIZE];
};
void push (stack *the_stack, double number) {
if(&&the_stack.top>=SIZE-1){
printf("error");
}else{
the_stack.numbers[&&the_stack.top++ ] = number;
}
}
int main (int argc, char **argv) {
if (argc != 1) {
fprintf (stderr, "Usage: %s\n", basename (argv[0]));
fflush (NULL);
exit (EXIT_FAILURE);
}
stack the_stack;
the_stack.top = EMPTY;
char buffer[1024];
for (;;) {
int scanrc = scanf ("%1023s", buffer);
if (scanrc == EOF) break;
assert (scanrc == 1);
if (buffer[0] == '#') {
scanrc = scanf ("%1023[^\n]", buffer);
continue;
}
char *endptr;
double number = strtod (buffer, &endptr);
if (*endptr == '\0') {
push (&the_stack, number);
}else if (buffer[1] != '\0') {
bad_operator (buffer);
}else {
do_operator (&the_stack, buffer);
}
}
return exit_status;
}
我是否忽略了一些非常基本的东西?
最佳答案
访问结构体成员时,有两个运算符:点运算符.
(用于非指针结构)和“箭头”运算符->
它用于指向结构的指针。
您的 push
函数中有一个指向结构的指针,因此您需要使用“箭头”运算符。
您的代码还存在其他问题,例如 push
函数中的双 & 符号。退出程序时您也不需要刷新任何文件,运行时将为您执行此操作。
关于c - 将结构传递给函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19487124/