아래에 작성된이 코드가 작동하는 이유를 설명해 주시겠습니까?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct node
{
int number;
struct node *next;
}
node;
int main(void)
{
node *first = NULL;
node *second = NULL;
node *third = NULL;
first = malloc(sizeof(node));
second = malloc(sizeof(node));
third = malloc(sizeof(node));
first->number =1;
first->next = second;
second->number =2;
second->next = third;
third->number = 3;
third->next = NULL;
printf("%d\n%d\n%d\n", first->number, second->number, third->number);
return 0;
}
내 이해에 따르면 노드 *에 메모리를 할당 할 때 노드 포인터가 노드 배열을 가리 키도록 기술적으로 허용합니다. 따라서 노드 *는 단일 노드에 비해 데이터 유형이 다르며 number와 next는 단일 노드에 독점적 인 구성 요소가됩니다. 그러나 first-> number와 first-> next는 모두 값을 할당 할 수있어 혼란 스럽습니다. 왜냐하면 첫 번째 노드로 초기화 된 * 이제 단일 노드 인 것처럼 액세스 할 수 있다는 의미이기 때문입니다.
내 이해에서 노드에 메모리를 할당 할 때 *
.NET Framework를 저장하기에 충분한 공간이있는 메모리 영역을 할당합니다 node
.
기술적으로 노드 포인터가 노드 배열을 가리 키도록 허용하고 있습니다. 따라서 노드 *는 단일 노드에 비해 데이터 유형이 다르며 number와 next는 단일 노드에 독점적 인 구성 요소가됩니다.
first = malloc(sizeof(node));
first
에 의해 제공된 메모리 영역에 대한 포인터 malloc
입니다. 여기에는 아무 관련이 없습니다 array
. first
다르게하는 노드를 참조한다 second
에서 노드와 다른 third
노드.
first->number =1;
first->next = second;
second->number =2;
second->next = third;
third->number = 3;
third->next = NULL;
printf("%d\n%d\n%d\n", first->number, second->number, third->number);
이 코드는 매우 간단합니다. 그는 3 개의 다른 노드를 만들고 값을 설정 number
하고 인쇄합니다.
연속 메모리 영역을 원하면 다음과 같이 쓸 수 있습니다. array = malloc(3*sizeof(node));
이 경우 메모리 영역은 연속적입니다. 당신은 구문을 사용할 수 있습니다 array[0]
참조하기 위해 first
, 노드를 array[1]
받는 참조 second
노드와 array[2]
받는 참조 third
노드입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다