C - 初始化结构数组 [英] C - initialize array of structs

查看:28
本文介绍了C - 初始化结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在初始化结构数组时遇到问题.我不确定我是否做得对,因为我得到了从不兼容的指针类型初始化"&从不兼容的指针类型赋值".我在代码中添加了这些警告,当我尝试从结构中打印数据时,我只会得到垃圾,例如@@###

I am having a problem initializing an array of structs. I'm not sure if I am doing it right because I get "initialization from incompatible pointer type" & "assignment from incompatible pointer type". I added in the code where I get these warnings, and when I try to print the data from the struct I just get garbage such as @@###

typedef struct
{
    char* firstName;
    char* lastName;
    int day;
    int month;
    int year;

}student;

//初始化数组

    student** students = malloc(sizeof(student));
    int x;
    for(x = 0; x < numStudents; x++)
    {
        //here I get: "assignment from incompatible pointer type" 
        students[x] = (struct student*)malloc(sizeof(student));
    }

    int arrayIndex = 0;

//添加结构

 //create student struct
        //here I get: "initialization from incompatible pointer type"
        student* newStudent = {"john", "smith", 1, 12, 1983};

        //add it to the array
        students[arrayIndex] = newStudent;
        arrayIndex++;

推荐答案

这是不正确的:

student** students = malloc(sizeof(student));

您不想要**.你想要一个 * 和足够的空间来容纳你需要多少学生

You do not want a **. You want a * and enough space for how ever many students you need

student *students = malloc(numStudents * sizeof *students); // or sizeof (student)
for (x = 0; x < numStudents; x++)
{
    students[x].firstName = "John"; /* or malloc and strcpy */
    students[x].lastName = "Smith"; /* or malloc and strcpy */
    students[x].day = 1;
    students[x].month = 12;
    students[x].year = 1983;
}

如果您仍想使用//add struct"部分中的代码,则需要更改该行:

If you still want to use the code in your "//add struct" section, you'll need to change the line:

student* newStudent = {"john", "smith", 1, 12, 1983};

student newStudent = {"john", "smith", 1, 12, 1983};

因为您试图用 student 类型的对象初始化指向 student 的指针,所以您得到了从不兼容的指针类型初始化".

You were getting "initialization from incompatible pointer type" because you were attempting to initialize a pointer to student with an object of type student.

这篇关于C - 初始化结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆