Created
December 25, 2019 19:04
-
-
Save ungarson/991bb62c846659f92e144573aae239e9 to your computer and use it in GitHub Desktop.
Struct with dynamic memory allocation in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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