[英]struct stack error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
Code (test.c):代码(test.c):
#include <stdio.h>
struct stack {
double a[100];
int maxSize = 100;
};
int main() {
return 0;
}
Compile command:编译命令:
gcc -Wall -o "test" "test.c"
Errors:错误:
gcc -Wall -o "test" "test.c" (in directory: /home/amey)
test.c:4:17: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
int maxSize = 100;
^
Compilation failed.
Why is this not compiling?为什么这不编译?
You cannot declare default values in a struct declaration in C. This is simply not allowed in the C language.您不能在 C 中的结构声明中声明默认值。这在 C 语言中是完全不允许的。
What you can do is this:你可以做的是:
...
int main()
{
struct stack mystack;
mystack.maxSize = 100;
...
or或者
...
int main()
{
struct stack mystack = {.maxSize = 100};
...
But anyway it doesn't make much sense to have a variable maxSize
because the size of a
is fixed to 100 anyway.但无论如何,它并没有多大意义,具有可变
maxSize
因为尺寸a
固定为100反正。 The proper way would be a #define MAXSIZE 100
or const int MAXSIZE = 1000;
正确的方法是
#define MAXSIZE 100
或const int MAXSIZE = 1000;
, and then declare double a[MAXSIZE];
, 然后声明
double a[MAXSIZE];
and drop the field maxSize
alltogether.并将字段
maxSize
删除。
That being said, you probably want something like this:话虽如此,你可能想要这样的东西:
#include <stdio.h>
#define MAXSTACKSIZE 100
// or
// const int MAXSIZE = 100;
struct stack {
double stack[MAXSTACKSIZE];
int stackpointer;
};
void InitializeStack(struct stack *thestack)
{
thestack->stackpointer = 0;
}
void push(struct stack *thestack, double value)
{
// to be written (3-4 lines including error checking)
}
double pop(struct stack *thestack)
{
// to be written (3-4 lines including error checking)
}
int main() {
struct stack mystack;
InitializeStack(&mystack);
push(&mystack, 1.234);
printf("%f\n", pop(&mystack)); // output should be 1.234
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.