简体   繁体   English

结构指针数组的问题

[英]Problems with array of pointers to struct

After defining the type student (which is a struct made of two arrays of characters and an int), I've created an array of pointers to student, which I need in order to modify its content inside of a series of functions. 在定义了Student类型(它是由两个字符数组和一个int组成的结构)之后,我创建了一个指向Student的指针数组,为了在一系列函数中修改其内容,需要使用该数组。

int main(void) 
{
    student* students[NUMBER_OF_STUDENTS];

    strcpy(students[0]->name, "test");
    strcpy(students[0]->surname, "test");
    students[0]->grade = 18;

    return EXIT_SUCCESS;
}

My problem is that this simple piece of code returns -1 as exit status after running. 我的问题是,这段简单的代码在运行后返回-1作为退出状态。 Why is that? 这是为什么?

The pointer students[0] is uninitialized. 指针students[0]未初始化。 Dereferencing it results in undefined behavior. 取消引用它会导致未定义的行为。

Initialize it with the address of a valid object before attempting to access it. 尝试访问它之前,请使用有效对象的地址对其进行初始化。

student test;
students[0] = &test;

strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;

Because it is UB. 因为是UB。 You have only pointer without the actual structs allocated. 您只有指针,没有分配实际的结构。

students[x] = malloc(sizeof(*students[0]));

or statically 或静态地

student s;
students[x] = &s;

or 要么

 students[x] = &(student){.name = "test", .surname ="test", .grade = 18};

The pointers are pointing to nowhere since you have not allocated any memory for them to point to. 指针指向无处,因为您尚未分配任何内存来指向它们。

int main(void) 
{
    student* students = (student*)malloc(sizeof(student)*[NUMBER_OF_STUDENTS]); \\malloc dynamically allocate heap memory during runtime

strcpy(students[0]->name, "test");
strcpy(students[0]->surname, "test");
students[0]->grade = 18;

return EXIT_SUCCESS;

} }

*Note Edit by marko -- Strictly the pointers are pointing to whatever was last in the stack location or register holding it - it may be nothing, or something you actually care about. * Note marko marko编辑-严格地,指针指向栈中最后的内容或保存它的寄存器-它可能什么也没有,或者您实际上关心的东西。 The joys of UB UB的欢乐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM