-2

I'm trying to load a txt file into memory but is not going right in line Video->client[cont].name = name;

ps: the txt client is like this

txt:
1 name1
2 name2
3 name3

and the code is:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct Client
{
    int number;
    char *name;
};

struct Loan
{
    int number;
    Client *client;
};

void check_error(FILE *arquivo)
{
    if(arquivo==NULL)
    {
        printf("Error to open file!");
        exit(0);
    }
}

void load_client(Loan *video)
{
    FILE *arquivo;
    arquivo=fopen("clientes.txt","rt");
    check_error(arquivo);
    int num,cont=0;
    char name[30];
    while(!feof(arquivo))
    {
    fscanf(arquivo,"%d %s " ,&num,&name); 
    video->client[cont].number=num;
    video->client[cont].name=name; //this part give error!!
    cont++;
    }
    for(int i=0;i<20;i++)
    {
        printf("%d %s\n",video->client[i].number, video->client[i].name);
    }
    fclose(arquivo);
}

int main()
{
    Loan *video=(Loan*)malloc(20*sizeof(Loan));
    video->client=(Client*)malloc(20*sizeof(Client));
    video->client->name=(char*)malloc(20*sizeof(char));
    load_client(video);
    return 0;
}

please somebody help me, ps: sorry about my inglish!

rockoder
  • 747
  • 11
  • 23
user3576248
  • 45
  • 2
  • 7

1 Answers1

0

In main(), you are creating 20 clients using following line:

video->client=(Client*)malloc(20*sizeof(Client));

So the next line should allocate memory for 20 client names. That is, following line should be in loop with access to each client as client[i]:

video->client->name=(char*)malloc(20*sizeof(char));

rockoder
  • 747
  • 11
  • 23