C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 在结构中动态存储数据的程序

在结构中动态存储数据的 C 程序

在本例中,您将学习使用动态内存分配来存储用户输入的信息。
要理解此示例,您应该了解以下C 编程 主题:
C 指针 C 动态内存分配 C 结构
该程序要求用户存储 noOfRecords 的值,并使用 malloc() 动态地为 noOfRecords 结构变量分配内存功能。

演示结构的动态内存分配

#include <stdio.h>
#include <stdlib.h>
struct course {
  int marks;
  char subject[30];
};
int main() {
  struct course *ptr;
  int noOfRecords;
  printf("Enter the number of records: ");
  scanf("%d", &noOfRecords);
  // Memory allocation for noOfRecords structures
  ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
  for (int i = 0; i < noOfRecords; ++i) {
    printf("Enter subject and marks:\n");
    scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
  }
  printf("Displaying Information:\n");
  for (int i = 0; i < noOfRecords; ++i) {
    printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
  }
  free(ptr);
  return 0;
}
输出
Enter the number of records: 2
Enter subject and marks:
Science 82
Enter subject and marks:
DSA 73
Displaying Information:
Science     82
DSA     73
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4