使用指针和动态结构时出错

时间:2014-11-13 20:46:21

标签: c

我正在尝试学习结构和指针。我正在创建一个程序,我正在使用动态结构。但我不明白为什么我的程序在运行“stampa”函数时崩溃。我一次又一次地阅读它,但我仍然不明白错误在哪里。 请你帮助我好吗?谢谢,对不起英语很差。

#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;
}

1 个答案:

答案 0 :(得分:2)

参数通过C中的值传递,因此如果要将指针作为参数传递给函数以初始化它,则需要添加另一级别的间接,即

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

您当前尝试在gestione函数中初始化add,但它只初始化其指针的本地副本。