C 编程数据结构用户输入无法初始化结构类型 Visual Studio

标签 c visual-studio data-structures

在我的 .h 文件中,

typedef struct {
int month;
int day;
}Date;

typedef struct {
char courseName[30];
char assignName[30];
int points;
Date duedate;
}QueData;

下面的内容位于 .c 文件中

int main(int argc, char argv[]) {

QuePtr priority_hw;
NodePtr FrontNode;
priority_hw = initQueue(10);

    char UserInput1[30], UserInput2[20];
int UserInput3, UserInput4, UserInput5;

printf("Please enter 1st Course name \n");
scanf("%s", &UserInput1);
printf("Please enter 1st Assignment name \n");
scanf("%s", &UserInput2);
printf("Please enter 1st Assignment's points  \n");
scanf("%d", &UserInput3);
printf("Please enter 1st Assignment's duedate month  \n");
scanf("%d", &UserInput4);
printf("Please enter 1st Assignment's duedate day  \n");
scanf("%d", &UserInput5);


printf("Entered Name: %s\n", UserInput1);
printf("Entered Website:%s", UserInput2);

Date duedate1 = { UserInput4, UserInput5 };
QueData assignment1 = { UserInput1, UserInput2, UserInput3, duedate1 };

但是在tasking1的初始化中, duedate1 下出现了红线。它说它不能用“日期”替换字符类型,我将其定义为具有日期和月份字段的结构。但正如您在 .h 文件中看到的,QueData 结构的第四个字段是“日期”。尽管如此,为什么它要求 char ? 我试过了

    QueData assignment1 = { UserInput1, UserInput2, UserInput3, {UserInput4, UserInput5} }; 

也是,但它会说“初始化值太多”。

但是,如果我这样做

QueData assignment1 = { "calc1", "hw5", 10, { 1, 11 } }; 

它有效。为什么当我将这些值更改为变量时它不起作用?

最佳答案

通常,像 "abc" 这样的字符串文字被视为指向 char 的指针。例如,以下代码将字符串文字视为指针

char *str = "hello";
printf( "%s\n", str );  // prints hello followed by a newline

但是,如果使用字符串文字来初始化字符数组,则根据 C11 规范

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

例如下面的代码

char str[6] = "hello";

会将字符串 "hello" 的字符(后跟 '\0')放入数组中。

但是,这种类型的初始化仅适用于字符串文字。您不能使用另一个数组的内容来初始化一个数组。例如,以下内容无效有效

char str1[6] = "hello";
char str2[6] = str1;    // this is NOT allowed

初始化str2的正确方法是使用strcpy,例如

char str1[6] = "hello";
char str2[6];
strcpy( str2, str1 );

所以初始化赋值1的正确方法是

Date duedate1 = { UserInput4, UserInput5 };
QueData assignment1 = { "", "", UserInput3, duedate1 };
strcpy( assignment1.courseName, UserInput1 );
strcpy( assignment1.assignName, UserInput2 );

关于C 编程数据结构用户输入无法初始化结构类型 Visual Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245244/

相关文章:

c - gmp 奇怪的行为不允许我编译新项目

c - ANSI 键序列

c++ - 与 Windows 投影文件系统 DLL/LIB 链接

unit-testing - 当 `Result`不是 `Copy`时,设计单元测试

data-structures - 具有最大 api 的双端队列?

c - 将简单的算牌功能重构为多种功能?

c - 无法在 C 中打印值

c++ - Visual Studio 中的多个主要 CPP 文件?

visual-studio - 安装 TFS Powertools 后出现 VS2008 错误

c - 学习如何在使用 scanf 时正确引用结构体字段 (C)