无法使结构在 C 中工作(使用 GCC)

标签 c gcc data-structures cs50

所以我刚刚练习 C 中的结构,遇到了一个大问题......我附上了代码和错误 我尝试运行的代码是将预定义值放入结构中,然后打印它。

代码

#include <stdio.h>
struct student
{
    int sroll;
    char sname[20];
    int stotal;
}
int main()
{
    struct student st;
    clrscr();
    st.sroll = 1;
    strcpy(sname, "Example");
    st.stotal = 700
    printf("\n Roll => %d", st.sroll);
    printf("\n Name => %d", st.sname);
    printf("\n Total Marks => %d", st.stotal);
    return 0;
}

错误

$ gcc -o strpre strpre.c
strpre.c:8:1: error: expected ‘;’, identifier or ‘(’ before ‘int’
    8 | int main()
      | ^~~
strpre.c: In function ‘main’:
strpre.c:11:5: warning: implicit declaration of function ‘clrscr’ [-Wimplicit-function-declaration]
   11 |     clrscr();
      |     ^~~~~~
strpre.c:13:5: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
   13 |     strcpy(sname, "Example");
      |     ^~~~~~
strpre.c:13:5: warning: incompatible implicit declaration of built-in function ‘strcpy’
strpre.c:2:1: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
    1 | #include <stdio.h>
  +++ |+#include <string.h>
    2 | struct student
strpre.c:13:12: error: ‘sname’ undeclared (first use in this function); did you mean ‘rename’?
   13 |     strcpy(sname, "Example");
      |            ^~~~~
      |            rename
strpre.c:13:12: note: each undeclared identifier is reported only once for each function it appears in
strpre.c:14:20: error: expected ‘;’ before ‘printf’
   14 |     st.stotal = 700
      |                    ^
      |                    ;
   15 |     printf("\n Roll => %d", st.sroll);
      |     ~~~~~~          
strpre.c:16:25: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
   16 |     printf("\n Name => %d", st.sname);
      |                        ~^   ~~~~~~~~
      |                         |     |
      |                         int   char *
      |                        %s

顺便说一句,我使用的是带有最新 GCC 版本的 CS50 IDE。

编辑:在我尝试了 @Robert 的修复后...它仍然不起作用... https://pastebin.ubuntu.com/p/mBjkR292wb/ 编辑2:我的错误没有添加分号

最佳答案

我想你漏掉了一个分号:

struct student
{
    int sroll;
    char sname[20];
    int stotal;
}; // <========================= missing ;

正如评论中所写,您还有另一个拼写错误:

strcpy(st.sname, "Example");

关于无法使结构在 C 中工作(使用 GCC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65824055/

相关文章:

c - 在运行时使用 gnuplot 从 c 绘图

c - 在 Linux 内核中赋值两个值

macos - 在 OSX 上安装 Go 时出现 Ld 错误

c - 二叉搜索树的递归

java - N-Queens 程序使用 LinkedStack 而不是使用递归

java - 链接数据和 ComboBox 项目的最佳方式

c++ - 我从 Wireshark 获得了 C 数组形式的数据,现在我在以正常形式解码它时遇到了麻烦

c - 如何使用多种开发语言

c++ - 关于条件编译 (ifndef) 的快速问题

c - 与 clang 相比,gcc 的具有一定字节数的 __builtin_memcpy 性能很糟糕