2014-11-13 2 views
0

저는 구조체와 포인터를 학습하려고합니다. 나는 동적 인 구조를 사용하고있는 프로그램을 만들고있다. 하지만 "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; 
} 

답변

2

인수는, 즉,

, C의 값에 의해 전달된다
void assign_pointer(T **p) 
{ 
    /* check p for null */ 
    *p = malloc(count * sizeof **p); 
} 

add 함수에서 현재 gestione을 초기화하려고 시도하지만 포인터의 로컬 복사본 만 초기화합니다.

+0

@ Tommy4 : 할 수는 있지만,'add' 함수 밖에서 초기화하지 않으므로'stampa'에서 읽는 것으로 정의되지 않은 동작을 호출합니다. 사실 포인터를 증가시킨 후에'index'를 사용하여 포인터를 색인 할 때'add'에서 정의되지 않은 동작을 호출합니다. 'index + 1' 객체 (즉, 1 객체)를 할당하기 때문에'index + 1'의 색인을 사용하는 것은 무효합니다. –

+0

좋아, 그럼 어디서 초기화해야합니까? – Tommy4

+0

@ Tommy4 : 어디서나 의미가 있습니다. 모든 함수가 포인터를 가져 가기 때문에 전역적일 필요는 없습니다. 가장 간단한 경로는'main'에서 초기화하고 그것을 전달하는 것입니다. –

관련 문제