2015-01-11 4 views
1

C에서 포인터가있는 중첩 구조를 사용하고 싶습니다. 나는이 코드를 작성하지만이 코드가 작동하지 않는 이유를 모른다. 사실 어떻게 두 번째 구조에 메모리를 할당 할 수 있습니까?C에 포인터가있는 중첩 구조

#include <stdio.h> 
#include <stdlib.h> 
struct address 
{ 
    int code; 
    char city[10]; 
}; 
struct student { 
    char name[10]; 
    struct address *ads; 
} *person1; 

int main() 
{ 

person1 = malloc(sizeof(struct student)); 
scanf("%s", person1->name); 
scanf("%d", &person1->ads->code); 
scanf("%s", person1->ads->city); 

printf("%s", person1->name); 
printf("%d", person1->ads->code); 
printf("%s", person1->ads->city); 
return 0; 
} 

참고 : "person1-> ads = malloc (sizeof (struct address)); 프로그램이 문제를 일으키고 작동을 멈췄습니다.


[코멘트에서 업데이트 :]

내가 DEV C를 사용 ++ v5.4.2

또한 포인터를 통해 저장 회원 메모리를 할당 할 필요가
+2

의 고정 anotated 버전입니다. 그래서 person1-> ads = malloc (sizeof (struct address))와 같은 것을 추가 할 필요가있다. –

+0

나는 짐작하고 테스트하지만 .. 문제가 생겼다. –

+0

이 레이아웃에서, 나는'ads '를 처음부터 포인터로 만들지 않을 것이다. 'struct student'에서'struct address ads;로 선언하고'person1-> ads '로 채 웁니다. – WhozCraig

답변

3

당신은 당신의 성공을 확인하지 않는

  1. 몇 poblems이 malloc.
  2. person1->ads의 경우 malloc을 입력하지 마십시오.
  3. scanf의 성공 여부를 확인하지 않았습니다.

이 당신은 광고 구성원에 대한 메모리를 할당하지 않은 코드

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

struct address 
{ 
    int code; 
    char city[10]; 
}; 

struct student 
{ 
    char name[10]; 
    struct address *ads; 
}; 

int main() 
{ 
    /* You don't need te struct to be global, and it's generally a bad idea, not always of course */ 
    struct student *person; 

    /* you should check that malloc succeeded otherwise undefined behavior would happen */ 
    person = malloc(sizeof(*person)); 
    if (person == NULL) 
    { 
     printf("cannot allocate memory\n"); 
     return -1; 
    } 

    /* you should check that scanf succeeded too */ 
    if (scanf("%9s", person->name) != 1) 
    /*  ^prevent buffer overflow */ 
    { 
     printf("Invalid, input\n"); 
     free(person); 
     return -1; 
    } 

    person->ads = malloc(sizeof(*(person->ads))); 
    if (person->ads == NULL) 
    { 
     printf("cannot allocate memory\n"); 
     /* on failure free successfuly allocated person */ 
     free(person); 
     return -1; 
    } 

    /* you should check that scanf succeeded too */ 
    if (scanf("%d", &person->ads->code) != 1) 
    { 
     printf("Invalid, input\n"); 

     free(person->ads); 
     free(person); 

     return -1; 
    } 

    /* you should check that scanf succeeded too */ 
    if (scanf("%9s", person->ads->city) != 1) 
    /*  ^prevent buffer overflow */ 
    { 
     printf("Invalid, input\n"); 

     free(person->ads); 
     free(person); 

     return -1; 
    } 

    printf("Name: %s\n", person->name); 
    printf("Code: %d\n", person->ads->code); 
    printf("City: %s\n", person->ads->city); 

    free(person->ads); 
    free(person); 

    return 0; 
} 
+0

감사합니다! 좋은 조언과 충고 :) –

+0

1+ 스캔을위한 1+ ... :-) – alk

+0

@AmirMohammadNasrollahi –

3

.

int main() 
{ 
    person1 = malloc(sizeof(struct student)); 
    person1->ads = malloc(sizeof(struct address)); 
    scanf("%s", person1->name); 
    scanf("%d", &person1->ads->code); 
    scanf("%s", person1->ads->city); 

    printf("%s", person1->name); 
    printf("%d", person1->ads->code); 
    printf("%s", person1->ads->city); 
    free(person1->ads); 
    free(person1); 
    return 0; 
} 
+0

테스트했지만 여전히 작동하지 않습니다 ... –

+0

@AmirMohammadNasrollahi,'int name [10];'을''char name [10];으로 변경하면 작동합니다. –

+0

@CoolGuy ohhh 죄송합니다 !! 내 실수! :) –

3

는 어떻게 두 번째 구조에 대한 메모리를 할당 할 수 있습니까? 예를 들어

첫 번째 구조에서했던 것과 같은 방법 : 힙에서 할당

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

struct address 
{ 
    int code; 
    char city[10]; 
}; 

struct student 
{ 
    char name[10]; 
    struct address * ads; 
}; 

int main(void) 
{ 
    struct student * person1 = malloc(sizeof * person1); 
    if (NULL == person1) 
    { 
    perror("malloc() failed for person1"); 
    } 
    else 
    { 
    person1->ads = malloc(sizeof * person1->ads); 
    if (NULL == person1->ads) 
    { 
     perror("malloc() failed for person1->ads"); 
    } 
    else 
    { 
     /* scan and print */ 

     free(person1->ads); 
    } 

    free(person1); 
    } 
} 
+0

오케이 알아! 하지만 어떻게? 나는 여러 가지 방법을 테스트하고 모두 작동하지 않습니다! : D –

+0

@AmirMohammadNasrollahi : 업데이트 된 답변을 참조하십시오. – alk

+0

좋은 방법과 나는 그것을 이해하지만 여전히 "person1-> 광고"를 식별하고 작동을 멈추는 데 문제가 있습니다. 난 왜 정말이 코드는이 컴파일러에서 작동하지 않는지 모르겠다. –