【发布时间】:2018-08-04 21:14:48
【问题描述】:
#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 chinese_seating *a 与 struct student **seating 以及二维数组。除此之外,我将如何使用 struct chinese_seating *a 来访问 2D 数组?我确实知道指针的基础知识,但我已经研究了几个小时并没有找到与工作的联系。
我知道这一行 printf("%s", listOfStudents[0][2].firstName); 打印 ***(假设用户输入 3,3 作为行/列)。只是我不知道如何在以后的方法中访问它。
【问题讨论】:
-
我猜你从提供的答案中解决了问题。
-
正如 coderredoc 在下面的回答中指出的那样,您已经尝试将不适合的内容分配给
a->seat。但即使它适合代码也不会让你高兴,因为struct student students[rowNum][columnNum];是本地 定义到函数seating()的,所以从这个函数返回的代码的那一刻所有内存a->seat都指向会变得无效。