while(l->next !=NULL) // I am pretty sure that this while loop is correct
l=l->next;
예,이 while
루프가 맞습니다. 루프가 완료되면 l
은 으로 목록의 마지막 요소를 가리 킵니다.
l->next = malloc(sizeof(int)) //hmm... is this correct way to allocate memory
할당량이 거의 맞습니다. 에 충분한 저장소를 할당하는 경우 int
을 보유하지만 실제로는 하나의 저장소를 보유 할 충분한 공간이 필요합니다. struct list
. 대신 l->next = malloc(sizeof(struct list));
을 사용하십시오.
l->next->val = newval; //not sure about this
여기에 오류가 없습니다. 이것은 다음 줄이 정확히 정확합니다.
l->next->next = NULL; //This should be fine
예, 괜찮습니다 ..이 부분의 코드는 이미 덮여 있었다 malloc()
,
l->next = malloc(sizeof(int)) //hmm... is this correct way to allocate memory
l->next->val = newval; //not sure about this
l->next->next = NULL; //This should be fine
여기에 사용되는 방법을 금지, 대부분 올바른 동안
그러나, 약간 이례적인 일이다. 새 메모리를 할당 할 때 포인터를 직접 l->next
에 할당 한 다음 초기화해야하기 때문입니다. 더 일반적으로 이루어집니다 무엇
는 todeclare 포인터와 같은 기능, 의 시작 부분에 struct list *tmp = NULL
및 할당 할 때, tmp
에 새 메모리를 할당 할 수 있습니다. 그런 다음 이 가리키는 새 목록 요소를 tmp
으로 초기화하고 만 초기화 한 다음 현재 초기화 된 새 목록 요소를 목록의 끝에 추가하십시오. 약간 더 많은 코드가 포함되지만 은 새 목록 요소 을 생성하고 목록의 끝에 요소를 추가하는 두 단계를 분리합니다. 이런 식으로 일을 또한
void add_to_list(struct list *l, int newval)
{
struct list *tmp = NULL;
if (!l) return; // If no valid list, return.
tmp = malloc(sizeof(struct list)); // Allocate new list element
tmp->val = newval; // and fill it up.
tmp->next = NULL; // End of the list always points nowhere.
while(l->next !=NULL) // find end of list.
l=l->next;
l->next = tmp; // Attach new list element to end.
return;
}
는 l->next
포인터를 통해 값을 할당에서 을 발생할 수있는 잠재적 인 혼란을 방지 할 수 있습니다.
'l-> next = malloc (sizeof (int))'실제로 메모리를 할당하는 올바른 방법이지만 충분하지는 않습니다. 전체'struct list'를 포함 할만큼 충분히 할당 할 필요가 있습니다. 이 라인을'l-> next = malloc (sizeof (* (l-> next)))로 바꾼다.' –