[英]pointer of struct and pointer inside that struct
我有一个问题,其中有一个结构将保存姓名、年龄和学生 ID。 我必须从用户那里获取输入并在不使用任何数组表示法的情况下生成该数量的结构。 然后每个结构的参数都应该从用户那里获取输入并同时打印出来。 这就像创建一个学生数据库。 结构是:
typedef struct
{
char *name;
char *std_id;
int age;
} student;
所以我的输入是这样的:
Number of students: 3
Name of the student1: Bro
std_id of the student1: 46845
age of the student1: 18
Name of the student2: kim
std_id of the student2: 46867
age of the student2: 19
Name of the student3: Sean
std_id of the student3: 46862
age of the student3: 18
而 output 就像:
Name of the student1 is: Bro
std_id of the student1 is: 46845
age of the student1 is: 18
Name of the student2 is: kim
std_id of the student2 is: 46867
age of the student2 is: 19
Name of the student3 is: Sean
std_id of the student3 is: 46862
age of the student3 is: 18
主要问题是我们不能在这个问题中使用任何数组。
我尝试通过搜索 inte.net 对问题进行编码是这段代码:
#include<stdio.h>
#include<string.h>
typedef struct
{
char *name;
char *std_id;
int age;
} students;
int main()
{
int num;
printf("Type the number of students:");
scanf("%d", &num);
students* ptr = malloc(num * sizeof(*ptr));
if(ptr == NULL)
{
printf("memory not free!");
return 0;
}
for(int i=0; i<num; i++)
{
printf("\nGive the name of the std %d:", i+1);
(ptr+i)->name = malloc(sizeof(char)*20);
if((ptr+i)->name == NULL)
{
printf("memory not free!");
return 0;
}
scanf("%s", (ptr+i)->name);
printf("Give the std_id of the std %d:", i+1);
(ptr+i)->std_id = malloc(sizeof(char)*10);
if((ptr+i)->std_id == NULL)
{
printf("memory not free!");
return 0;
}
scanf("%s", (ptr+i)->std_id);
printf("Give the age of std %d:", i+1);
scanf("%d", (ptr+i)->age);
}
for(int i=0; i<num; i++)
{
printf("\nThe name of the std %d: %s", i+1, (ptr+i)->name);
printf("\nThe std_id of the std %d: %s", i+1, (ptr+i)->std_id);
printf("\nThe age of the std %d: %d", i+1, (ptr+i)->age);
}
return 0;
}
使用此代码,这就是我的控制台的样子:
Type the number of students:3
Give the name of the std 1:Sean
Give the std_id of the std 1:45
Give the age of std 1:23
Process returned -1073741819 (0xC0000005) execution time : 23.131 s
Press any key to continue.
在这里,我试图首先运行name
变量的代码。 如果运行正确,我将实现其他变量,如name
变量。 但是当我运行这段代码时,程序只接受一个输入就退出了。 我只是无法自己解决问题。 任何有关如何解决此问题的帮助将不胜感激。
students* ptr = malloc((sizeof(int) + sizeof(char) * 50) * num);
这根本没有任何意义,我什至不明白你想做什么。 如果你想分配一个结构数组,那么你必须这样做:
students* ptr = malloc(num * sizeof(*ptr));
或同等学历:
students* ptr = malloc( sizeof(students[num]) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.