Struct in C + Malloc

108 views Asked by At

I have this [UPDATED]

typedef struct Cerchi { 
    char nome[4];
    int x; //coordinate centro
    int y; //coordinate centro
    int r; //raggio
}cerchio;

   cerchio *leggi_file ( FILE *fp)
{
            char buffer[100]; 
            int i=0;    
            cerchio *bufcer;
            bufcer=(cerchio *)malloc(sizeof (int)*10000000);               
                while(fgets(buffer, sizeof(buffer), fp)!= NULL) //Fino a che file non รจ null
                         {  
                         //bufcer=realloc(bufcer, sizeof(int)*100);
                         sscanf(buffer, "%s %d %d %d",bufcer[i].nome,&bufcer[i].x,&bufcer[i].y,&bufcer[i].r);
        /*stampa di controllo*/          printf("\n%s %d %d %d",bufcer[i].nome,bufcer[i].x,bufcer[i].y,bufcer[i].r); 
                         i++;                
                         }
                         return bufcer;
                
                                          
}

This function is working. That's the UPDATED main

int main(int argc, char *argv[]) {
    FILE *fp;
if (argc < 2) {
    printf("Mancano parametri da tastiera\n"); //Sempre >=1 parametri passati
    exit(1);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
    printf("Impossibile aprire il file\n");
    exit(1);
}
    struct Cerchi *bufcer = NULL;
bufcer = leggi_file(fp);
stampa(bufcer); 
//vettore = leggi_file(FILE *fp);    E R R O R E
fclose(fp);

return 0;
}

I'm not able to print my *bufcer struct in this function

    void stampa(bufcer)
{
int i;
for (i=0;i<50;i++)
 {
 printf("\n%s %d %d %d",bufcer[i]->nome,bufcer[i]->x,bufcer[i]->y,bufcer[i]->r); 
 }
}

Please try to help me, tomorrow morning I have an exam about it [UPDATED] Which error I'm doing? Can you try to solve it and help me? Thanks a lot...

2

There are 2 answers

4
Sourav Ghosh On
  1. Do not cast return value of malloc().
  2. Always check the return value of sscanf() to ensure all the elements got scanned successfully.
  3. Change stampa( struct Cerchi *bufcer); to stampa(bufcer); This is a function call not a function definition or declaration. Also, add struct Cerchi *bufcer = NULL; inside main() before calling stampa().
  4. You are not using the return value of leggi_file (). As per your logic, you need to collect the value in bufcer. Change your code to

    bufcer = leggi_file(fp);
    
  5. Always check for the success of malloc() before using the returned pointer.
2
Amol Saindane On

You have to use -> operator when accessing structure elements, so your printf will be as

printf("\n%s %d %d %d",bufcer[i]->nome,bufcer[i]->x,bufcer[i]->y,bufcer[i]->r);

Also, -> operator use for scanf()

You need to pass & of structure to pass structure pointer