C-构造指针阵列的问题



定义了类型的学生(由两个字符和一个int制成的结构(后,我为学生创建了一系列指针,我需要修改它它的内容在一系列功能中。

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;
}

我的问题是,这条简单的代码在运行后将-1返回-1作为退出状态。为什么?

指针students[0]是未初始化的。提出它会导致不确定的行为。

在尝试访问有效对象的地址初始化它。

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

因为它是ub。您只有没有分配实际结构的指针。

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

或静态

student s;
students[x] = &s;

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

指针无处指向,因为您没有分配任何记忆来指向。

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;

}

*注释Marko的编辑 - 严格来说,指针指向堆栈位置中的最后一个或持有它的注册 - 可能没有什么,或者您实际关心的东西。UB的喜悦

最新更新