gpt4 book ai didi

c++ - 为结构变量赋值

转载 作者:行者123 更新时间:2023-11-30 21:42:14 24 4
gpt4 key购买 nike

当我以这种方式为 s.rollno 赋值时,它不起作用

#include<stdio.h>
struct student{
int rollno;
int marks;
}s ;
s.rollno = 2;

int main(){

printf("%d",s.rollno);

}

但是如果我在 main 中为 s.rollno 赋值,它就可以工作

#include<stdio.h>
struct student{
int rollno;
int marks;
}s ;

int main(){
s.rollno = 2;


printf("%d",s.rollno);

}

最佳答案

你不能写

 s.rollno = 2;

在全局范围内,作为单独的语句。所有语句都需要出现在某个函数内,该函数可以执行它们。

但是,您可以在定义时初始化该值,例如

struct student {
int rollno;
int marks;
} s = {.rollno = 2};

关于c++ - 为结构变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com