#include <string.h>
#include <stdio.h>
struct student{
char last[25] ;
char first[25];
};
struct seating {
struct student **seat;
};
//Set the first and last name to default values
void student_init_default(struct student *s ) {
strcpy(s->last_name,"***");
strcpy(s->first_name,"***");
}
void seating(int rowNum, int columnNum, struct seating *a ){
//Instantiate a 2D array specfied by the parameters
struct student students[rowNum][columnNum];
a->seat = students;
//Initialize each element to the default
for(int rows = 0; rows < rowNum; rows++){
for(int columns = 0; columns < columnNum; columns++){
student_init_default(&students[rows][columns]);
}
}
}
void main() {
struct seating room;
struct student student;
int row, col, rowNum, columnNum;
char student_info[30];
// Ask a user to enter a number of rows for an classroom seating
printf ("Please enter a number of rows for an classroom seating.");
scanf ("%d", &rowNum);
// Ask a user to enter a number of columns for an classroom seating
printf ("Please enter a number of columns for an classroom seating.");
scanf ("%d", &columnNum);
// seating
seating(rowNum, columnNum, &room);
}
首先,我是 C 的初学者。我的问题是使用指针。这段代码的要点是创建一个struct student 的二维数组,然后通过将默认值设置为名字和姓氏来填充该数组。我要问的是,是否有人可以就如何连接参数 struct classroom_seating *a 和 struct student **seating 以及二维数组。除此之外,我将如何使用 struct classroom_seating *a 访问二维数组?我知道指针的基础知识,但我已经研究了几个小时,但没有找到工作的联系。
我知道这一行 printf("%s", listOfStudents[0][2].firstName); 打印 ***(假设用户为行/列输入 3,3 ).只是我不知道如何在以后的方法中访问它。
最佳答案
a->seat = students;
编译器明确指出错误
error: cannot convert 'student [rowNum][columnNum]' to 'student**' in assignment
a->seat = students;
^
是错误的,因为在这里您将二维数组分配给双指针。二维数组衰减为 struct student (*)[]
,然后您尝试将其分配给 struct student **
。
相反,您应该自己创建交错数组并使用它。
a->seat = malloc(sizeof(struct student*)* rowNum);
if(!a->seat){
perror("malloc");
exit(EXIT_FAILURE);
}
for(int i = 0; i< rowNum; i++){
a->seat[i] = malloc(sizeof(struct student)* columnNum);
if(!a->seat[i]){
perror("malloc");
exit(EXIT_FAILURE);
}
}
之后,您可以像以前一样传递每个 struct student
实例的地址并对其进行更改。
进一步阐明您可能关注的组织
struct seating room;
这里的room
是一个包含双指针的结构体实例。就是这样。该指针指向没有意义的地方。它包含不确定值(垃圾值)。现在您想分配一些内存并使用它。这是在函数
seating
中完成的。因为它只是一个指针,所以你分配了rowNum
struct student *
的内存,为什么要struct student*
?因为那样会依次指向一系列struct student
变量实例。成功分配后,现在您拥有了内存,并且它不是自动存储持续时间 - 它会在函数
seating
结束时保留。其存储期限超出功能范围。请注意一件事,
strcpy(s->last_name,"***");
但结构定义中没有last_name
变量。这将是last
。其他成员变量也一样。进行更改后,您将像这样传递
struct student
的实例:-for(int rows = 0; rows < rowNum; rows++){ for(int columns = 0; columns < columnNum; columns++){ student_init_default(&a->seat[rows][columns]); } }
您正在尝试为
a->seat
分配一些不适合(不可能)的东西。但即使它适合它也是错误的,因为struct student students[rowNum][columnNum];
是在函数seating()
中局部定义的,所以此时代码从此函数返回的所有内存a->seat
指向都将变得无效。访问它将是未定义的行为。 (alk 指出了这一点)。
关于arrays - C 将指针与结构的二维数组一起使用以及如何使用指针访问它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971153/