By little improvement on others good answers, I want to introduce this version.
- We must always check return of
malloc()
to ensure success or its failure on allocate some desired memory location(s) on the Heap.
If it fails, any try to access that unallocated memory cause Undefined Behavior.
- We must not cast return type of
malloc()
in C Why not cast return of malloc() its dangerous, see first answer.
#include <stdlib.h>
explicitly when using malloc()
.
Code
#include <stdio.h>
#include <stdlib.h>
struct Employee
{
char *name;
int salary;
};
int main(){
struct Employee emp[3];
printf("Enter name, salary\n");
int i;
for(i=0;i<3;i++){
emp[i].name = malloc(40*sizeof(char));
if (emp[i].name != NULL){
scanf("%s %d", emp[i].name, &emp[i].salary);
}else{
///If this accur, try to access inside below for loop is UB
printf("Cant allocate Memory for name[%d]\n", i);
}
}
printf("\nOutput:\n");
for(i=0;i<3;i++)
{
printf("%s: %d\n", emp[i].name, emp[i].salary);
}
///Free allocated memory
printf("Free allocated memory\n");
for(i=0;i<3;i++)
{
free(emp[i].name);
}
return 0;
}
Compile and Run
gcc -Wall so.c -o so && ./so
[Hint]
You must insert an space or hit enter, between Name and salary integer.
Although this works but i recommend to separate scanf()
for each section to get user input for pair of name, salary with hit enter key after each, this is readable, i think.
scanf("%s", emp[i].name);
scanf("%d", &emp[i].salary);
[Notes]
Try to avoid using scanf()
. Thanks for @Jonathan Leffler for providing this link that i steal from
I recommend to take a look at scanf() leaves the new line char in the buffer, leaving a leading space when scan character " %c"
inside scanf()
malloc()
documentation
[ToDo]
- Some Research on possible similarity between
"%c"
, "%d"
in scanf()
behavior in scanning, remove buffer.
- provide some explain, links on Heap, Stack.