Tommy4
Tommy4

Reputation: 21

Error using pointers and dynamic structures

i'm trying lo learn structures and pointers. I am creating a program where i am using a dynamic structure. But i don't understand why my program crash when it runs the "stampa" function. I've read it again and again but i still don't understand where is the error. Could you please help me? Thanks and sorry for the poor english.

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    int day;
    int month;
    int year;
} DATE_T;
typedef struct
{
    DATE_T date;
    int codice;
    int codiceProdotto;
    int n;
} GESTIONE_T;
GESTIONE_T *gestione;
int index = 0;
void add(GESTIONE_T *gestione);
void stampa(GESTIONE_T *gestione);
int main()
{
    printf("1 - Add ");
    add(gestione);
    printf("2 - Printf");
    stampa(gestione);
    return 0;
}
void add(GESTIONE_T *gestione)
{
    gestione = (GESTIONE_T *)malloc((index + 1) * sizeof(GESTIONE_T));
    if (gestione == NULL)
    {
        printf("Errore durante l'allocazione della memoria");
        exit(EXIT_FAILURE);
    }
    printf("\nInserisci il tuo codice identificativo: ");
    scanf("%d", &gestione[index].codice);
    printf("\nInserisci il codice del prodotto: ");
    scanf("%d", &gestione[index].codiceProdotto);
    printf("\nInserisci il numero di oggetti venduti: ");
    scanf("%d", &gestione[index].n);
    printf("test 3 : %d", gestione[index].n);
    index++;
    printf("\nInserisci la data nel formato GG/MM/YY: ");
    scanf("%d/%d/%d",
          &gestione[index].date.day,
          &gestione[index].date.month,
          &gestione[index].date.year);
    return;
}
void stampa(GESTIONE_T *gestione)
{
    int i;
    for (i = 0; i < index; i++)
        printf("Code: %d - Codice prodotto: %d - Numero: ",
               (gestione + index)->codice,
               (gestione + index)->codiceProdotto /*gestione[0].n)*/);
    return;
}

Upvotes: 0

Views: 41

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124692

Arguments are passed by value in C, so if you want to pass a pointer as an argument to a function in order to initialize it you'll need to add another level of indirection, i.e.,

void assign_pointer(T **p)
{
    /* check p for null */
    *p = malloc(count * sizeof **p);
}

You currently attempt to initialize gestione in your add function, but it only initializes its local copy of the pointer.

Upvotes: 2

Related Questions