I have defined a structure
struct subject
{
char name[100];
int year;
};
and since I need n
of these and I have to use malloc
I did the following in my main function:
int n, i;
scanf("%d", &n);
struct subject *ptr = malloc(n*sizeof(struct subject));
Unfortunately when I try to input something with this code:
for(i = 0; i < n; i++)
{
gets((ptr + i)->name);
scanf("%d", (ptr + i)->year);
}
It crashes after I type the first name. The task requires the use of malloc
.
Here's the whole code (unfortunately it's in my native language so it's a little bit different)
#include <stdio.h>
#include<stdlib.h>
#ifndef DEBUG
#define DEBUG(...)printf(_VA_ARGS_)
#endif
struct kolegij
{
char naziv[100];
int semestar;
};
int main(){
int brPredmeta, i;
scanf("%d", &brPredmeta);
struct kolegij *ptr = malloc(brPredmeta*sizeof(struct kolegij));
if(ptr == NULL)
{
printf("error\n");
return 0;
}
for(i = 0; i < brPredmeta; i++)
{
//gets(ptr->naziv);
gets((ptr + i)->naziv);
scanf("%d", &(ptr + i)->semestar);
getchar();
}
for(i = 0; i < brPredmeta; i++)
{
printf("%s\n", ptr[i].naziv);
printf("%d\n", ptr[i].semestar);
}
return 0;
}
With regards to the duplicate issue. I believe this shouldn't be a duplicate since it's related to structs and pointers. I had issues with scanfs before and I haven't considered this as a solution so I think it shouldn't be flagged as a duplicate.