ft_lstnew

jaehlee·2025년 4월 27일

Libft

목록 보기
17/26

linked list 설명

배열(Array) & 연결리스트(Linked List)
해당 페이지에 설명해두었음.

ft_lstnew를 구현하기 위해 libft.h파일에

typedef struct s_list
{
	void			*content;
	struct s_list	*next;
}					t_list;

이 구조체를 추가해야한다.

1. ft_lstnew란?


t_lstnew는 주어진 content를 저장하는 새로운 t_list 구조체 노드를 동적으로 생성하는 함수이다.
생성된 노드는 content를 저장하고 next 포인터는 NULL로 초기화한다.

2. 함수 프로토타입

t_list *ft_lstnew(void *content)

3. 함수구현

#include "libft.h"

t_list	*ft_lstnew(void *content)
{
	t_list	*new;

	new = (t_list *)malloc(sizeof(t_list));
	if (!new)
		return (NULL);
	new->next = NULL;
	new->content = content;
	return (new);
}

반환값

생성 성공시 새로 생성된 노드의 포인터를 리턴해준다.
메모리 할당 실패시 NULL을 리턴해준다.

사용예시


int main(void)
{
	t_list *node;
	char *str = "Hello, Linked List!";

	node = ft_lstnew((void *)str);

	if (!node)
	{
		printf("Memory allocation failed.\n");
		return (1);
	}

	printf("Node content: %s\n", (char *)(node->content)); // "Hello, Linked List!" 출력
	printf("Node next: %p\n", (void *)(node->next));        // NULL
	free(node);
	return (0);
}
profile
공부하는 개발자

0개의 댓글