I am new to programming in general and to C
in particular.
I am trying to write a program that uses an array of structs, but I am experiencing problems if that struct contains strings.
Somehow the compiler crashes after the user has given the last input.
The struct below is just a simplified version containing only one item, because the problem seems to be reading strings into the array. Any help is much appreciated, thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* name;
}student;
int main()
{
int size;
printf("enter number of entries\n");
scanf("%d" , &size);
student* all=malloc(size*sizeof(student));
int i;
for(i=0;i<size;i++)
{
printf("enter name\n");
scanf("%s" , all[i].name);
}
return 0;
}
Before taking input scanf("%s" , all[i].name);
, you need to allocate memory to all[i].name
.
An example-
for(i=0;i<size;i++)
{
all[i].name=malloc(20*sizeof(*(all[i].name)));
if(all[i].name!=NULL){
printf("enter name\n");
scanf("%19s" , all[i].name);
}
}
//use these strings
for(i=0;i<size;i++){
free(all[i].name); //free the allocated memory
}
free(all);
Or in your structure instead of char *
,declare name
as a char
array (if you don't want to use dynamic allocation)-
typedef struct{
char name[20]; //give any desired size
}student;
/* no need to free in this case */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With