Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created December 25, 2019 19:04
Show Gist options
  • Save ungarson/991bb62c846659f92e144573aae239e9 to your computer and use it in GitHub Desktop.
Save ungarson/991bb62c846659f92e144573aae239e9 to your computer and use it in GitHub Desktop.
Struct with dynamic memory allocation in c
#include <stdio.h>
#include <stdlib.h>
struct course {
int mark;
char subject[30];
} mark;
struct course *ptr; // we don't allocate memory at that point because we don't know amount yet
int numberOfRecords;
int main() {
printf("Enter amount of courses: ");
scanf("%d", &numberOfRecords);
ptr = (struct course*) malloc(numberOfRecords * sizeof(struct course)); // allocating here
for (register int i = 0; i < numberOfRecords; i++) {
printf("Enter the course name and the mark: ");
scanf("%s %d", &(ptr + i)->subject, &(ptr + i)->mark);
}
printf("\nResult:\n");
for (register int i = 0; i < numberOfRecords; i++) {
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->mark);
}
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment