gpt4 book ai didi

C99 | (BItfield) 结构中的结构无法使用 name1.name2.variable 进行选择

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:34 24 4
gpt4 key购买 nike

如何解决这个错误?我想要一个数组,我可以在其中扫描“学生”的数据并因此使用结构。问题是,另一个结构中的位域结构失败了。

有没有什么办法可以解决这个问题,而不改变代码的大部分结构?只想修复可以选择位域(日、月等)的问题。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

#define MAX 10
#define MAXCHAR 30

char comma;

struct date {
unsigned int day:5;
unsigned int month:4;
unsigned int year:11; //funktioniert bis yr 2047;
};

struct student {
unsigned long matriculation_number;
char first_name[MAXCHAR];
char last_name[MAXCHAR];
struct date birthdate;
}Student[MAX];

/*
void scan_student(void) {
b
} */

int main(void) {

int i = 0;
printf("------------------------------\nGeben Sie alle benötigten Daten ein\n");
printf("Vorname: ");
fgets(Student[i].first_name, MAXCHAR, stdin);

printf("Nachname: ");
fgets(Student[i].last_name, MAXCHAR, stdin);

printf("Matrikelnummer: ");
scanf(" %lu", &Student[i].matriculation_number);

printf("Geburtstdatum (DD.MM.YYYY): ");
scanf(" %u%c%u%c%u", &Student.birthdate.day, &comma, &Student.birthdate.month, &comma, &Student.birthdate.year);
printf("\n");


return EXIT_SUCCESS;
}

错误日志:

student.c: In function ‘main’:
student.c:42:26: error: cannot take address of bit-field ‘day’
scanf(" %u%c%u%c%u", &Student[i].birthdate.day, &comma, &Student[i].birthdate.month, &comma, &Student[i].birthdate.year);
^
student.c:42:61: error: cannot take address of bit-field ‘month’
scanf(" %u%c%u%c%u", &Student[i].birthdate.day, &comma, &Student[i].birthdate.month, &comma, &Student[i].birthdate.year);
^
student.c:42:98: error: cannot take address of bit-field ‘year’
&Student[i].birthdate.day, &comma, &Student[i].birthdate.month, &comma, &Student[i].birthdate.year);

最佳答案

虽然您不能将位域成员传递给 scanf,但您可以将临时变量传递给 scanf,然后毫无问题地将它们分配给位域:

unsigned char day = 0, month = 0;
unsigned short year = 0;
scanf(" %hhu%c%hhu%c%hu", &day, &comma, &month, &comma, &year);
Student.birthdate.day = day;
Student.birthdate.month = month;
Student.birthdate.year = year;

请注意,这确实涉及缩小,因此您可能有一个成功的 scanf 然后无法将其完整值存储在位域中。

鉴于进一步的评论指出您不允许使用 tmp 步骤,这对于设置此任务的人来说是完全不合理的,您根本不能使用 scanf。但是,您可以单独读取字符串,然后使用 strtoul 或类似工具将数字标记转换为可直接分配给位域的返回值。我真的不推荐这样做,但如果这是作业或类似任务的要求,这是可能的。

根据要求:C11 specification 7.21.6.1 节第 7 段描述了本例中使用的长度修饰符 hhh。这些允许指定要读取的整数类型的长度,其中hhchar的长度,h是长度的短。将这些与 d i o u xX 组合允许指定所有内置整数类型以供 (f)scanf 读取。

关于C99 | (BItfield) 结构中的结构无法使用 name1.name2.variable 进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54162413/

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