Array of structure with strings

I defined the structure

struct subject
{
    char name[100];
    int year;
};

and since I need one nof them, 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 enter something with this code:

for(i = 0; i < n; i++)
{
   gets((ptr + i)->name);
   scanf("%d", (ptr + i)->year);
}

Failure to enter first name. The task requires use malloc.

Here is the whole code (unfortunately, it is in my native language, it is so slightly 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;
}

Regarding the duplication of the question. I believe this should not be duplication, as it is related to structures and pointers. I had problems with scanfs before, and I did not see this as a solution, so I believe that this should not be marked as duplicate.

+4
source share
1

Malloc void. , . malloc :

int n, i;
scanf("%d", &n);
struct subject *ptr = (struct subject*) malloc(n*sizeof(struct subject));

:

for(i = 0; i < n; i++)
{
   gets((ptr + i)->name);
   scanf("%d", &((ptr + i)->year));
}
-6

All Articles