Você está na página 1de 26

🔰

Libft
📚 Acelera — Libft

Meus próprios vídeos sobre as funções da Libft rodando

Libft 42sp
Share your videos with friends, family, and the world

https://youtube.com/playlist?list=PLLYBHe5RzNItMJBwCZqeoMB39-L4ilay
8

Bibliotecas Estáticas

uso das diretivas do preprocessador #ifndef, #define e #endif, também chamadas de *Include


Guards* (em uma adaptação para o português significaria "proteção de inclusão"). Para um
melhor entendimento destas instruções explicarei "de dentro para fora", isto é, primeiro
o #define e em seguida o par #ifndef ... #endif.

A instrução #define é usada em C para definir macros, isto é, pequenas tarefas executadas


durante a compilação do código. Estas macros podem ser valores fixos — como
#define TAMANHO = 10 — ou pequenas instruções — como #define MAX(a, b) a>b ? a : b —
que facilitam a vida do programador, seja "memorizando" para ele pequenas instruções que
não merecem uma função ou pra reduzir o número de comandos digitados. Quando usamos
o define com apenas um argumento (como visto acima, #define _MYPRINT_LIB_) apenas
define para o preprocessador C que existe uma variável chamada _MYPRINT_LIB_.

Já o par #ifndef ... #endif faz parte de "um pacote maior" de diretivas do preprocessador,


são elas:

#if - Verificar se a expressão a seguir é verdadeira ou não;

#elif - Abreviação de ;

else if

#ifdef - Verifica se uma próxima variável foi definida (pela diretiva );

#define

#ifndef - Verifica se uma próxima variável não foi definida (pela diretiva );

#define

#else - Funciona como um  comum;


else

Libft 1
#endif - Marca o fim do bloco;

Basicamente estas instruções funcionam como ifs ... else comum, porém definem que trecho
de código será ou não incluído durante a compilação, desta forma podemos escrever um
código voltado apenas para uma arquitetura e outro código mais genérico ou até mesmo
diferenciar a compilação para cada sistema operacional.

Você por acaso já se perguntou qual a diferença de se utilizar as aspas ou o sinal de


maior/menor? Quando utilizamos um include que se utiliza dos sinais de maior/menos ao
redor do nome da biblioteca estamos indicando para o preprocessador que busque estes
arquivos de cabeçalho em uma conjunto de diretórios predefinidos (no GNU/Linux geralmente
dentro de /usr/lib), enquanto o outro modo (com aspas) busca apenas no diretório corrente.
Desta forma utilizamos os sinal de maior/menor que para bibliotecas instaladas no sistema e
aspas para bibliotecas escritas por nos.

Bibliotecas Estáticas Simples


Dando continuidade ao assunto de bibliotecas estáticas e compartilhadas,
neste artigo irei ensinar como escrever uma biblioteca etática simples (um
único arquivo) na poderosa e universal linguagem C. Esse é um assunto
http://mindbending.org/pt/bibliotecas-estaticas-simples

Compilação
gcc -c ft_memcpy.c //flag c

ar rcs banana.a ft_memcpy.o

gcc teste-ft_memcpy.c banana.a

./a.out

C Programming: Makefiles
Learn to construct a basic Makefile to automate building C programs.

https://www.youtube.com/watch?v=GExnnTaBELk&ab_channel=BarryBrow
n

http://wiki.icmc.usp.br/images/0/0a/ApostilaMakefiles2011.pdf

Lista Libft
bzero - zero a byte string

void bzero(void *s, size_t n);

Libft 2
The bzero() function erases the data in the n bytes of the memory
starting at the location pointed to by s, by writing zeros (bytes
containing '\0') to that area.

RETURN VALUE

None.

De acordo com o manual, esta função grava n bytes zerados na string s. Se n for zero,
ft_bzero não faz nada. Outra maneira de dizer isso é que faremos uma string de tamanho ne
preencheremos cada posição de índice com um 0. Usamos nossa função ft_memset criada
anteriormente para fazer isso. Revise ft_memset para entender como ele funciona e observe
os parâmetros que fornecemos aqui quando o chamamos. Definimos com antecedência para
preencher qualquer string de tamanho n com 0s.

memcpy - copy memory area

void *memcpy(void *restrict dest, const void *restrict src, size_t n);

The memcpy() function copies n bytes from memory area src to


memory area dest. The memory areas must not overlap. Use
memmove(3) if the memory areas do overlap.

RETURN VALUE

The memcpy() function returns a pointer to dest.

memccpy - copy memory area

void *memccpy(void *restrictdest, const void *restrictsrc,int c, size_t n);

The memccpy() function copies no more than n bytes from memory


area src to memory area dest, stopping when the character c is
found. If the memory areas overlap, the results are undefined.

RETURN VALUE

The memccpy() function returns a pointer to the next character in dest


after c, or NULL if c was not found in the first n characters of src.

De acordo com o manual, esta função copia bytes da string src para a string dst. Se o
caractere c (conforme convertido em um caractere sem sinal) ocorrer na string src, a cópia

Libft 3
será interrompida e um ponteiro para o byte após a cópia de c na string dst será retornado.
Caso contrário, n bytes são copiados e um ponteiro NULL é retornado. As strings de origem e
destino não devem se sobrepor, pois o comportamento é indefinido. * /
/ * Iniciamos esta função da mesma forma que fizemos em nossa função ft_memcpy.
Declaramos uma variável de contador size_t i que será usada para mover através das
posições de índice de nossas strings fundidas char e usaremos essa variável em comparação
com nosso size_t n fornecido. Também criamos duas variáveis de ponteiro char nas quais
colocaremos nossos parâmetros casted dst e src dentro. Definimos i como 0 para começar da
posição inicial do índice e colocamos a versão fundida de nossos parâmetros dst e src em
suas respectivas variáveis. Em seguida, passamos para o nosso loop. * /
/ * Enquanto nosso contador variável i é menor que o n dado, continuaremos nosso loop.
Dentro, definimos a posição de índice i de src2 na posição de índice i de dst2. Se o caractere
não assinado src2 convertido na posição do índice i for igual ao c fornecido, que também é
convertido para um char não assinado, então retornamos imediatamente um ponteiro casted
char para a posição do índice depois dele em nosso parâmetro dst original fornecido. Se
nunca encontrarmos c antes de i não ser menor que n, retornaremos NULL. *

memmove - copy memory area

void *memmove(void *dest, const void *src, size_t n);

The memmove() function copies n bytes from memory area src to


memory area dest. The memory areas may overlap: copying takes
place as though the bytes in src are first copied into a
temporary array that does not overlap src or dest, and the bytes
are then copied from the temporary array to dest.

RETURN VALUE

The memmove() function returns a pointer to dest.

memset - fill memory with a constant byte

void *memset(void *s, int c, size_t n);

The memset() function fills the first n bytes of the memory area
pointed to by s with the constant byte c.

RETURN VALUE

The memset() function returns a pointer to the memory area s.

Libft 4
Esta função é uma cópia da função memset na biblioteca string.h.
De acordo com o manual, a função memset grava len bytes do valor c (convertidos para
um caracter não assinado) na string b. Esta função retorna seu primeiro argumento. * /
Começamos criando uma string char de p. Isso é o que usaremos para manter uma
versão fundida de nosso parâmetro void b. Definimos p igual a uma versão char cast de
b. Se você não está familiarizado com a conversão de tipo, é uma maneira de converter
uma variável de um tipo de dados para outro tipo de dados. Em seguida, iniciamos nosso
loop. ft_memset precisa confiar no tamanho de len que é passado para seu parâmetro e
precisa trabalhar em uma parte geral da memória, não apenas em uma string terminada
em '\ 0', então não podemos ter a condição de nosso loop com base na ideia usual de que
chegaremos ao fim de uma string. Portanto, neste caso, dizemos que, desde que o len
fornecido seja maior que 0, continuaremos o loop. Em seguida, retrocedemos pela string
p, colocando o int c dentro de cada posição de índice. Fazemos len-1 porque estamos
compensando o término '\ 0' no final da string que não queremos substituir. Nós
decrementamos len e então começamos o loop novamente até que len não seja mais
maior que 0. Então retornamos b.

memchr - scan memory for a character

void *memchr(const void *s, int c, size_tn);


void *memrchr(const void *s, int c, size_tn);
void *rawmemchr(const void *s, int c);

The memchr() function scans the initialn bytes of the memory


area pointed to bys for the first instance of c. Both c and the
bytes of the memory area pointed to bys are interpreted as
unsigned char.

The memrchr() function is like the memchr() function, except that


it searches backward from the end of then bytes pointed to bys
instead of forward from the beginning.

The raw memchr() function is similar to memchr(): it assumes


(i.e., the programmer knows for certain) that an instance ofc
lies somewhere in the memory area starting at the location
pointed to bys, and so performs an optimized search forc (i.e.,
no use of a count argument to limit the range of the search). If
an instance ofc is not found, the results are unpredictable.
The following call is a fast means of locating a string's
terminating null byte:

char *p = rawmemchr(s, '\0');

RETURN VALUE

The memchr() and memrchr() functions return a pointer to the


matching byte or NULL if the character does not occur in the
given memory area.

The rawmemchr() function returns a pointer to the matching byte,


if one is found. If no matching byte is found, the result is
unspecified.

Libft 5
memcmp - compare memory areas

int memcmp(const void *s1, const void *s2, size_t n);

The memcmp() function compares the first n bytes (each


interpreted as unsigned char) of the memory areas s1 and s2.

RETURN VALUE

The memcmp() function returns an integer less than, equal to, or


greater than zero if the first n bytes of s1 is found,
respectively, to be less than, to match, or be greater than the
first n bytes of s2.

For a non zero return value, the sign is determined by the sign of
the difference between the first pair of bytes (interpreted as
unsigned char) that differ in s1 and s2.

Ifn is zero, the return value is zero.

De acordo com o homem, esta função compara a string de bytes s1 com a string de bytes s2.
Presume-se que ambas as strings tenham n bytes de comprimento. A função ft_memcmp
retorna zero se as duas strings são idênticas, caso contrário, retorna a diferença entre os dois
primeiros bytes diferentes (tratados como valores de caracteres não assinados, de forma que
'\ 200' seja maior que '\ 0', por exemplo). Strings de comprimento zero são sempre idênticos. *
/

/ * Começamos criando duas variáveis de ponteiro char que colocaremos versões char cast
de nossos parâmetros s1 e s2 dentro. Também criamos uma variável i size_t para contar
através das posições de índice de str1 e str2, bem como a usamos para comparar com o
parâmetro n que também é um size_t. Definimos i igual a 0 e colocamos as versões fundidas
de s1 e s2 em str1 e str2. Em seguida, iniciamos nosso loop. * /
/ * Desde que i seja menor que o n dado, queremos que nosso loop continue. Mas se em
qualquer ponto antes disso, e se alcançarmos uma posição de índice onde o caractere em
str1 não é o mesmo que str2, queremos retornar imediatamente a diferença entre os dois
bytes casted char não assinados diferentes. Se i atingir o ponto em que não é menor que n e
ainda não encontrarmos bytes diferentes, retornaremos um 0 para dizer que

ambas as strings de byte são iguais. * /

strlen - calculate the length of a string

size_t strlen(const char *s);

The strlen() function calculates the length of the string pointed


to by s, excluding the terminating null byte ('\0').

Libft 6
RETURN VALUE

The strlen() function returns the number of bytes in the string


pointed to by s.

strcpy, strncpy - copy a string

char *strcpy(char *restrictdest, const char *src);


char *strncpy(char *restrictdest, const char *restrictsrc, size_tn);

The strlcpy() and strlcat() functions copy and concatenate strings respectively.


They are designed to be safer, more consistent, and less error prone replacements
for strncpy(3) and strncat(3). Unlike those functions, strlcpy() and strlcat()
take the full size of the buffer (not just the length) and guarantee to
NUL-terminate the result (as long as size is larger than 0 or, in the case of strlcat(),
as long as there is at least one byte free in dst). Note that a byte for the NUL
should be included in size. Also note that strlcpy() and strlcat() only operate on
true ''C'' strings. This means that for strlcpy() src must be NUL-terminated and
for strlcat() both src and dst must be NUL-terminated.

The strlcpy() function copies up to size - 1 characters from the NUL-terminated


string src to dst, NUL - terminating the result.

The strlcat() function appends the NUL-terminated string src to the end of dst.


It will append at most size ap- strlen(dst) - 1 bytes, NUL-terminating the result.

RETURN VALUE

The strlcpy() and strlcat() functions return the total length of the string


they tried to create. For strlcpy() that means the length of src.
For strlcat() that means the initial length of dst plus the length of src.
While this may seem somewhat confusing, it was done to make truncation detection
simple.

Note, however, that if strlcat() traverses size characters without finding a NUL,


the length of the string is considered to be size and the destination string
will not be NUL-terminated (since there was no space for the NUL).
This keeps strlcat() from running off the end of a string. In practice this
should not happen (as it means that either size is incorrect or that dst is not a
proper ''C'' string). The check exists to prevent potential security problems in
incorrect code.

strchr, strrchr, strchrnul - locate character in string

Libft 7
char *strchr(const char *s, intc);
char *strrchr(const char *s, intc);

The strchr() function returns a pointer to the first occurrence


of the characterc in the strings.

The strrchr() function returns a pointer to the last occurrence


of the characterc in the strings.

The strchrnul() function is like strchr() except that if c is not


found ins, then it returns a pointer to the null byte at the end
ofs, rather than NULL.

Here "character" means "byte"; these functions do not work with


wide or multibyte characters.

RETURN VALUE

The strchr() and strrchr() functions return a pointer to the


matched character or NULL if the character is not found. The
terminating null byte is considered part of the string, so that
ifc is specified as '\0', these functions return a pointer to
the terminator.

The strchrnul() function returns a pointer to the matched


character, or a pointer to the null byte at the end ofs (i.e.,
s+strlen(s)) if the character is not found.

strstr, strcasestr - locate a substring

char *strstr(const char *haystack, const char *needle);


char *strcasestr(const char *haystack, const char *needle);

The strstr() function finds the first occurrence of the substring


needle in the string haystack. The terminating null bytes ('\0')
are not compared.

The strcasestr() function is like strstr(), but ignores the case


of both arguments.

RETURN VALUE

These functions return a pointer to the beginning of the located


substring, or NULL if the substring is not found.

strstr, strcasestr, strnstr -- locate a substring in a string

char*strstr(const char*big,const char*little);

char*strcasestr(const char*big,const char*little);

Libft 8
char*strnstr(const char*big,const char*little,size_t len);

The strstr() function locates the first occurrence of the null-terminated


stringlittle in the null-terminated stringbig.

The strcasestr() function is similar tostrstr(), but ignores the case of


both strings.

The strcasestr_l() function does the same asstrcasestr() but takes an


explicit locale rather than using the current locale.

The strnstr() function locates the first occurrence of the null-termi-


nated string little in the string big, where not more than len characters
are searched. Characters that appear after a `\0' character are not
searched. Since the strnstr() function is a FreeBSD specific API, it
should only be used when portability is not a concern.

RETURN VALUE

If little is an empty string, big is returned; if little occurs nowhere


in big, NULL is returned; otherwise a pointer to the first character of
the first occurrence of little is returned.

A função strnstr () localiza a primeira ocorrência do termo-nulo


string nated little na string big, onde não mais do que len caracteres são pesquisados. Os
caracteres que aparecem após um caractere `\ 0 'não são pesquisados. Visto que a função
strnstr () é uma API específica do FreeBSD, ela só deve ser usada quando a portabilidade
não for uma preocupação.

strcmp, strncmp - compare two strings

int strcmp(const char *s1, const char *s2);


int strncmp(const char *s1, const char *s2, size_t n);

The strcmp() function compares the two strings s1 and s2. The
locale is not taken into account (for a locale-aware comparison,
see strcoll(3)). The comparison is done using unsigned
characters.

strcmp() returns an integer indicating the result of the


comparison, as follows:

• 0, if the s1 and s2 are equal;

• a negative value if s1 is less than s2;

• a positive value if s1 is greater than s2.

The strncmp() function is similar, except it compares only the


first (at most) n bytes of s1 and s2.

RETURN VALUE

Libft 9
The strcmp() and strncmp() functions return an integer less than,
equal to, or greater than zero if s1 (or the first n bytes
thereof) is found, respectively, to be less than, to match, or be
greater than s2.

/ * Semelhante a ft_strcmp, o manual diz que esta função compara lexicograficamente as


strings terminadas em NULL s1 e s2 que são passadas para os parâmetros das funções. A
função retorna um número inteiro maior que, igual a ou menor que 0, dependendo se a string
s1 é maior, igual ou menor que a string s2. A comparação é feita novamente usando
caracteres sem sinal, de forma que '\ 200' seja maior que '\ 0'. A diferença, entretanto, entre
ft_strncmp e ft_strcmp é que iremos apenas pesquisar a string s1 em sua enésima posição. O
n é fornecido nos parâmetros. * /
/ * Primeiro declaramos nossa variável de contador i como um size_t. Fazemos isso porque o
parâmetro que consideramos para n é um size_t. Precisaremos comparar nosso valor give n
com nosso valor i, então eles devem ser iguais. * /

/ * Definimos i como 0 para nos colocar no início de nossa string quando iniciamos nosso
loop. Em seguida, verificamos se nosso n dado é igual a 0. Se for, retornamos 0. Se não,
começamos nosso loop, que requer três condições para ser verdadeiro para acontecer.
Queremos que nosso loop aconteça contanto que nossa string não tenha alcançado seu final
E enquanto o caractere na posição i em s1 é o mesmo que o caractere na posição i em s2 E
enquanto nossa variável de contador i é menor que n - 1. Nós subtraia 1 do n fornecido
porque uma variável size_t é freqüentemente usada para uma função de alocação de
memória e terá o tamanho total da string. Subtraímos 1 para compensar o fato de que o
tamanho_t dado não deve ser dado como 0. Se encontrarmos uma diferença nos caracteres,
ou nossa variável i se tornar do mesmo tamanho que n menos 1, ou chegarmos ao final de
s1, terminamos o loop. Em seguida, retornamos a diferença entre o caractere atual em s1 na
posição i e o caractere atual em s2 na posição i. NOTA: Nós selecionamos os personagens
como personagens sem sinais, como o homem explicou. * /

atoi, atol, atoll - convert a string to an integer

int atoi(const char *nptr);


long atol(const char *nptr);
long long atoll(const char *nptr);

The atoi() function converts the initial portion of the string pointed
to by nptr to int. The behavior is the same as strtol(nptr, NULL, 10);
except that atoi() does not detect errors.

The atol() and atoll() functions behave the same as atoi(), except that
they convert the initial portion of the string to their return type
of long or long long.

RETURN VALUE

The converted value or 0 on error.

Libft 10
/ * Esta é uma recriação da função atoi em C. Pegamos uma string de caracteres que
deveriam ser um número convertido em um int. * De acordo com o manual, "A função atoi
converte a parte inicial do ponto da string em representação de str em int." * /

/ * Começamos criando três variáveis. O primeiro é o que conterá o nosso resultado que será
devolvido. Usamos long porque é garantido ser capaz de armazenar, no mínimo, valores que
se encontram no intervalo de -2147483647 e 2147483647. Sinal será o que usaremos para
tornar o int negativo no caso de ser um número negativo que é colocado na corda. Nós o
temos como um longo, então podemos multiplicar nosso resultado por ele no final. Em
seguida, temos um int i sem sinal, que será o contador de nossa string. Para compensar uma
string incrivelmente longa, usamos um int sem sinal para poder usar seu intervalo positivo
estendido sobre um int assinado. Iremos definir todos eles como 0, exceto para o nosso sinal,
que definimos como 1 para usar com base na aparência de um símbolo negativo em nossa
string * /

/ * A primeira coisa que queremos que nossa função faça é nos certificar de pular qualquer
tipo de espaçamento que possa ser encontrado no início da string. * /

/ * Uma vez passado o espaçamento extra, se ele existir, estamos verificando se existe um
símbolo negativo no início do número que estaremos convertendo. se vemos um símbolo
negativo ou positivo, ajustamos de acordo. Se for negativo, definimos nosso sinal igual a -1
para multiplicar pelo nosso resultado quando o retornarmos. * /

Aqui, convertemos nossa string de caracteres de char para int, desde que sejam
números. Se o caractere em que estamos atualmente for um número, nós o convertemos
em seu valor numérico ascii. Para o primeiro caractere res é sempre definido como 0.
Multiplicamos 10 imediatamente por nosso res para definir a colocação do dígito onde
deveria estar. Em seguida, subtraímos o valor numérico do caractere 0 na tabela ascii do
nosso número de caractere atual. Isso o define para seu valor numérico ASCII. Em
seguida, recomeçamos nosso loop e continuamos até encontrar um caractere que não
seja um número. * /

/ * Por último, retornamos o valor res multiplicado pelo valor do sinal para retornar o número
com base no fato de ser negativo ou não. OBSERVAÇÃO: temos int entre parênteses para
converter o resto * do sinal em um int para que ele possa ser retornado como um int. * /

isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph,


islower, isprint, ispunct, isspace, isupper, isxdigit, isalnum_l,
isalpha_l, isascii_l, isblank_l, iscntrl_l, isdigit_l, isgraph_l,
islower_l, isprint_l, ispunct_l, isspace_l, isupper_l, isxdigit_l
- character classification functions

int isalnum(int c);


int isalpha(int c);
int iscntrl(int c);
int isdigit(int c);
int isgraph(int c);
int islower(int c);
int isprint(int c);
int ispunct(int c);

Libft 11
int isspace(int c);
int isupper(int c);
int isxdigit(int c);

int isascii(int c);


int isblank(int c);

int isalnum_l(int c, locale_t locale);


int isalpha_l(int c, locale_t locale);
int isblank_l(int c, locale_t locale);
int iscntrl_l(int c, locale_t locale);
int isdigit_l(int c, locale_t locale);
int isgraph_l(int c, locale_t locale);
int islower_l(int c, locale_t locale);
int isprint_l(int c, locale_t locale);
int ispunct_l(int c, locale_t locale);
int isspace_l(int c, locale_t locale);
int isupper_l(int c, locale_t locale);
int isxdigit_l(int c, locale_t locale);

int isascii_l(int c, locale_t locale);

These functions check whether c, which must have the value of an


unsigned char or EOF, falls into a certain character class
according to the specified locale. The functions without the
"_l" suffix perform the check based on the current locale.

The functions with the "_l" suffix perform the check based on the
locale specified by the locale object locale. The behavior of
these functions is undefined if locale is the special locale
object LC_GLOBAL_LOCALE (see duplocale(3)) or is not a valid
locale object handle.

The list below explains the operation of the functions without


the "_l" suffix; the functions with the "_l" suffix differ only
in using the locale object locale instead of the current locale.

isalnum()
checks for an alphanumeric character; it is equivalent to
(isalpha(c) || isdigit(c)).

isalpha()
checks for an alphabetic character; in the standard "C"
locale, it is equivalent to (isupper(c) || islower(c)).
In some locales, there may be additional characters for
which isalpha() is true—letters which are neither
uppercase nor lowercase.

isascii()
checks whether c is a 7-bit unsigned char value that fits
into the ASCII character set.

isblank()
checks for a blank character; that is, a space or a tab.

iscntrl()
checks for a control character.

isdigit()
checks for a digit (0 through 9).

isgraph()
checks for any printable character except space.

islower()

Libft 12
checks for a lowercase character.

isprint()
checks for any printable character including space.

ispunct()
checks for any printable character which is not a space or
an alphanumeric character.

isspace()
checks for white-space characters. In the "C" and "POSIX"
locales, these are: space, form-feed ('\f'), newline
('\n'), carriage return ('\r'), horizontal tab ('\t'), and
vertical tab ('\v').

isupper()
checks for an uppercase letter.

isxdigit()
checks for hexadecimal digits, that is, one of
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F.

RETURN VALUE

The values returned are nonzero if the character c falls into the
tested class, and zero if not.

toupper, tolower, toupper_l, tolower_l - convert uppercase or


lowercase

int toupper(int c);


int tolower(int c);

int toupper_l(int c, locale_t locale);


int tolower_l(int c, locale_t locale);

These functions convert lowercase letters to uppercase, and vice


versa.

If c is a lowercase letter, toupper() returns its uppercase


equivalent, if an uppercase representation exists in the current
locale. Otherwise, it returns c. The toupper_l() function
performs the same task, but uses the locale referred to by the
locale handle locale.

If c is an uppercase letter, tolower() returns its lowercase


equivalent, if a lowercase representation exists in the current
locale. Otherwise, it returns c. The tolower_l() function
performs the same task, but uses the locale referred to by the
locale handle locale.

If c is neither an unsigned char value nor EOF, the behavior of


these functions is undefined.

The behavior of toupper_l() and tolower_l() is undefined if


locale is the special locale object LC_GLOBAL_LOCALE (see
duplocale(3)) or is not a valid locale object handle.

Libft 13
RETURN VALUE

The value returned is that of the converted letter, or c if the


conversion was not possible.

calloc — a memory allocator

void *calloc(size_t nelem, size_t elsize);

The calloc() function shall allocate unused space for an array of


nelem elements each of whose size in bytes is elsize. The space
shall be initialized to all bits 0.

The order and contiguity of storage allocated by successive calls


to calloc() is unspecified. The pointer returned if the
allocation succeeds shall be suitably aligned so that it may be
assigned to a pointer to any type of object and then used to
access such an object or an array of such objects in the space
allocated (until the space is explicitly freed or reallocated).
Each such allocation shall yield a pointer to an object disjoint
from any other object. The pointer returned shall point to the
start (lowest byte address) of the allocated space. If the space
cannot be allocated, a null pointer shall be returned. If the
size of the space requested is 0, the behavior is implementation-
defined: either a null pointer shall be returned, or the behavior
shall be as if the size were some non-zero value, except that the
behavior is undefined if the returned pointer is used to access
an object.

RETURN VALUE

Upon successful completion with both nelem and elsize non-zero,


calloc() shall return a pointer to the allocated space. If either
nelem or elsize is 0, then either:

* A null pointer shall be returned and errno may be set to an


implementation-defined value, or

* A pointer to the allocated space shall be returned. The


application shall ensure that the pointer is not used to
access an object.

Otherwise, it shall return a null pointer and set errno to


indicate the error.

A função calloc () deve alocar espaço não utilizado para um array de elementos nelem, cada
um cujo tamanho em bytes é elsize. O espaço deve obrigatoriamente ser inicializado para
todos os bits 0.

A ordem e a contiguidade do armazenamento alocado por chamadas sucessivas para calloc () não
são especificadas. O ponteiro retornado se a alocação for bem-sucedida deve ser alinhado adequa
damente de modo que possa ser atribuído a um ponteiro para qualquer tipo de objeto e então usado
para acessar tal objeto ou uma matriz de tais objetos no espaço alocado (até que o espaço seja e
xplicitamente liberado ou realocado).

Libft 14
Cada uma dessas alocações produzirá um indicador para um objeto separado de qualquer outro ob
jeto. O ponteiro retornado deve apontar para o início (endereço de byte mais baixo) do espaço al
ocado. Se o espaço não puder ser alocado, um ponteiro nulo deve ser retornado. Se o tamanho do e
spaço solicitado for 0, o comportamento é definido pela implementação: ou um ponteiro nulo deve
ser retornado, ou o comportamento deve ser como se o tamanho fosse algum valor diferente de zer
o, exceto que o comportamento é indefinido se o valor retornado ponteiro é usado para acessar um
objeto.

strdup, strndup, strdupa, strndupa - duplicate a string

char *strdup(const char *s);

char *strndup(const char *s, size_t n);


char *strdupa(const char *s);
char *strndupa(const char *s, size_t n);

The strdup() function returns a pointer to a new string which is


a duplicate of the string s. Memory for the new string is
obtained with malloc(3), and can be freed with free(3).

The strndup() function is similar, but copies at most n bytes.


If s is longer than n, only n bytes are copied, and a terminating
null byte ('\0') is added.

strdupa() and strndupa() are similar, but use alloca(3) to


allocate the buffer. They are available only when using the GNU
GCC suite, and suffer from the same limitations described in
alloca(3).

RETURN VALUE

On success, the strdup() function returns a pointer to the


duplicated string. It returns NULL if insufficient memory was
available, with errno set to indicate the error.

A função strdup () retorna um ponteiro para uma nova string que é


uma duplicata da string s. A memória para a nova corda é
obtido com malloc (3), e pode ser liberado com free (3).
Em caso de sucesso, a função strdup () retorna um ponteiro para o
string duplicada. Ele retorna NULL se memória insuficiente era
disponível, com errno definido para indicar o erro.

ft_substr

Function name ft_substr


Prototype
char *ft_substr(char const *s, unsigned int start, size_t len);
Turn in files -
Parameters
#1. The string from which to create the substring.
#2. The start index of the substring in the string ’s’.
#3. The maximum length of the substring.
Return value

Libft 15
The substring. NULL if the allocation fails.
External functs. malloc
Description
Allocates (with malloc(3)) and returns a substring
from the string ’s’. The substring begins at index ’start’ and is of
maximum size ’len’.

Começamos declarando três variáveis. Os dois primeiros serão contadores que usaremos
para percorrer nossas strings. A terceira é a nova string para a qual alocaremos memória
para retornar a concatenação de nossas strings de parâmetro. * / / * Definimos ambas as
variáveis de contador como 0, pois queremos que ambos os contadores comecem no início
de suas respectivas strings. Nós então alocar memória usando a função malloc com uma
combinação de usar nossas funções ft_strlen feitas anteriormente. Usamos a função ft_strlen
em ambas as strings de parâmetro para descobrir o comprimento total de uma concatenação
e adicionamos 1 a esse comprimento adicionado para ter certeza de que podemos adicionar
uma terminação '\ 0'. Se a alocação falhar, retornaremos NULL. * / / * Se a alocação
funcionar, começamos nossa concatenação de nossas cadeias de caracteres fornecidas. *
Começamos com s1 com um loop de string padrão dizendo que, contanto que não tenhamos
atingido o final da string, continue. Colocamos o índice de nossa nova string str e de nosso
parâmetro s1 em i, que neste momento é 0. Em seguida, percorremos o comprimento de s1,
colocando cada caractere em s1 em str. Assim que terminar, continuamos para o próximo
loop. * / / * Este próximo loop é exatamente igual ao loop anterior, exceto que você deve
observar nosso uso da variável de contador j. j é atualmente igual a 0 neste ponto em nossa
função. Para nossa nova string str, definimos o índice igual ao contador anterior i mais nosso
novo contador j. Isso nos mantém na posição de índice em que terminamos quando nosso
loop anterior terminou, pois será o valor i estava no final do loop anterior mais o valor atual de
j de 0. Usamos j para definir o índice de nossa string s2 e deixar o loop vai até chegarmos ao
final de s2. Assim que o final de s2 for alcançado, adicionamos um terminador '\ 0' ao final de
nossa nova string e * retorna a nova string que é uma nova concatenação de nossos
parâmetros. * /

ft_strjoin

Function name ft_strjoin


Prototype char *ft_strjoin(char const *s1, char const *s2);
Turn in files -
Parameters
#1. The prefix string.
#2. The suffix string.
Return value
The new string. NULL if the allocation fails.
External functs. malloc
Description
Allocates (with malloc(3)) and returns a new string, which is the
result of the concatenation of ’s1’ and ’s2’.

Nome da função ft_strjoin


Protótipo char * ft_strjoin (char const * s1, char const * s2);
Entregar arquivos -
Parâmetros
# 1. A string de prefixo.

Libft 16
# 2. A string de sufixo.
Valor de retorno
A nova string. NULL se a alocação falhar.
Funções externas. Malloc
Descrição
Aloca (com malloc (3)) e retorna uma nova string, que é o
resultado da concatenação de 's1' e 's2'.

Começamos declarando três variáveis. Os dois primeiros serão contadores que usaremos
para percorrer nossas strings. A terceira é a nova string para a qual alocaremos memória
para retornar a concatenação de nossas strings de parâmetro. Definimos ambas as variáveis
de contador como 0, pois queremos que ambos os contadores comecem no início de suas
respectivas strings. Nós então
alocar memória usando a função malloc com uma combinação de usar nossas funções
ft_strlen feitas anteriormente. Usamos a função ft_strlen em ambas as strings de parâmetro
para descobrir o comprimento total de uma concatenação e adicionamos 1 a esse
comprimento adicionado para ter certeza de que podemos adicionar uma terminação '\ 0'. Se
a alocação falhar, retornaremos NULL. *
/ * Se a alocação funcionar, começamos nossa concatenação de nossas cadeias de
caracteres fornecidas. Começamos com s1 com um loop de string padrão dizendo que,
contanto que não tenhamos atingido o final da string, continue. Colocamos o índice de nossa
nova string str e de nosso parâmetro s1 em i, que neste momento é 0. Em seguida,
percorremos o comprimento de s1, colocando cada caractere em s1 em str. Assim que
terminar, continuamos para o próximo loop. * /

/ * Este próximo loop é exatamente igual ao loop anterior, exceto que você deve observar
nosso uso da variável de contador j. j é atualmente igual a 0 neste ponto em nossa função.
Para nossa nova string str, definimos o índice igual ao contador anterior i mais nosso novo
contador j. Isso nos mantém na posição de índice em que terminamos quando nosso loop
anterior terminou, pois será o valor i estava no final do loop anterior mais o valor atual de j de
0. Usamos j para definir o índice de nossa string s2 e deixar o loop vai até chegarmos ao final
de s2. Assim que o final de s2 for alcançado, adicionamos um '\ 0' de terminação ao final de
nossa nova string e retornamos a nova string que é uma nova concatenação de nossos
parâmetros. * /

ft_strtrim

Function name ft_strtrim


Prototype char *ft_strtrim(char const *s1, char const *set);
Turn in files -
Parameters
#1. The string to be trimmed.
#2. The reference set of characters to trim.
Return value
The trimmed string. NULL if the allocation fails.
External functs. malloc
Description
Allocates (with malloc(3)) and returns a copy of ’s1’ with the
characters specified in ’set’ removed from the beginning and the end of the string.

Libft 17
Nome da função ft_strtrim
Protótipo char * ft_strtrim (char const * s1, char const * set);
Entregar arquivos -
Parâmetros
1. A string a ser aparada.
2. O conjunto de referência de caracteres para aparar.
Valor de retorno
A string aparadas. NULL se a alocação falhar.
Funções externas. Malloc
Descrição
Aloca (com malloc (3)) e retorna uma cópia de 'S1' com os caracteres
especificados em 'set' removidos desde o início e o fim da string.

ft_split

Function name ft_split


Prototype char **ft_split(char const *s, char c);
Turn in files -
Parameters
#1. The string to be split.
#2. The delimiter character.
Return value
The array of new strings resulting from the split.
NULL if the allocation fails.
External functs. malloc, free
Description
Allocates (with malloc(3)) and returns an array
of strings obtained by splitting ’s’ using the
character ’c’ as a delimiter. The array must be
ended by a NULL pointer.

Esta função alocará memória e retornará uma 'nova' tabela de strings (todas terminadas
por '\ 0', a tabela também) como resultado da divisão da string dada pelo caractere c
fornecido. Se a alocação de memória falhar em qualquer ponto, a função retornará NULL.
E um exemplo dessa função é ft_strsplit ("* olá * colegas *** alunos ", ''). Isso deve
retornar uma tabela que divide a string int ["olá", "colega", "alunos"]. Esta função deve ser
realizada em três partes. Começaremos na função ft_strsplit na parte inferior. Colocamos
ft_strsplit no final do nosso código porque, para usar outras funções que criamos
especificamente para ele, temos que nos certificar de que as executamos antes de
chegarmos à nossa função real. * /

/ * A primeira função que temos é uma função de contagem de palavras. Fazemos isso
porque precisaremos descobrir quantas strings colocaremos em nossa tabela que serão
retornadas da função ft_strsplit. Queremos isso para quando alocarmos memória para a
mesa. * /
/ * Começamos criando duas variáveis. O primeiro é um int i sem sinal que usaremos para
percorrer a string fornecida a ft_strsplit. Usamos unsigned no caso de conseguirmos uma
string ridiculamente longa. Também criamos uma variável de contador que usaremos para
contar as palavras na string e então a retornaremos. NOTA: Esta função retorna um int
estático. Uma variável estática como forma de evitar o uso de variáveis globais. Uma variável
estática mantém seu valor entre as invocações. Usamos isso para casos em que uma função

Libft 18
precisa manter algum estado entre as invocações. Definimos ambas as nossas variáveis
como 0 e iniciamos nossa função. * /

/ * Entramos em nosso loop while e ele é executado em loop, desde que não tenhamos
chegado ao final da string fornecida. Dentro de nosso loop, temos outro loop while que diz
que, desde que a posição do índice em que estamos tenha o mesmo caractere do nosso
parâmetro c, queremos ir além dele. Este é o mesmo caractere c pelo qual a função ft_strsplit
irá dividir a string. Portanto, queremos pular esse caractere até encontrar nossa primeira
palavra real. Se, quando nosso loop while termina de passar por c caracteres, não
alcançamos o final da string dada, então queremos aumentar nosso contador de palavras.
Sabemos que temos algo que não é o caractere mantido pela variável c e queremos separar
isso da string. Em seguida, vamos para outro loop while que passará por todos os caracteres
em nossa palavra até encontrar outra instância do caractere mantido pela variável c. Se
encontrarmos um e não chegarmos ao fim de nossa string, começamos o loop novamente e
continuamos até chegar ao fim, contando todas as palavras ao longo do caminho. Em
seguida, retornamos a variável cntr que nos dirá quantas palavras existem em nossa string. *
/

A próxima função é uma variação da função ft_strdup que criamos anteriormente. De acordo
com o homem, a função ft_strdup aloca memória suficiente para uma cópia da string dada,
faz a cópia e retorna um ponteiro para ela. A função ft_strndup copia no máximo n (nosso
parâmetro size_t) caracteres da string fornecida, sempre NULL terminando a string copiada. *
/
/ * Começamos criando uma variável string para a qual alocaremos memória * e que
retornaremos como resultado desta função. Alocamos a memória para esta string usando o
parâmetro n desta função. Obtemos esse parâmetro de nossa função ft_strsplit. É o
comprimento de uma das palavras que dividimos em uma mesa. Adicionamos 1 a isso na
função malloc para garantir espaço para um '\ 0' de terminação. Em seguida, verificamos se a
alocação de memória falhou. Se isso acontecer, iremos retornar NULL. Se a alocação for
bem-sucedida, queremos colocar nossa palavra em nossa nova string str. Fazemos isso
usando nossa função ft_strncpy criada anteriormente. Fornecemos ft_strncpy nossa string
'fresca' alocada na memória, a string de parâmetro s (que é tirada de ft_strsplit mas foi
colocada na função ft_strndup no índice a palavra que queremos colocar em str iniciará) e o
parâmetro size_t n. Em seguida, certifique-se de adicionar um caractere de terminação ao
final de nossa nova string e, em seguida, retorná-lo. * /

Com as funções anteriores feitas, agora estamos prontos para começar nossa função
real, ft_strsplit * /

Começamos criando três variáveis de contador. Usaremos essas três variáveis para
localizar posições de índice dentro de nossa string de parâmetro s. Também criamos uma
guia de variável char **. Esta variável é para nossa tabela que conterá nossas strings
divididas. Definimos as variáveis i e k como 0 e, então, alocamos memória para nossa
tabela. É aqui que usamos nossa função ft_cntwrd acima, para descobrir quanto espaço
precisamos alocar para nossa tabela. Se a alocação falhar, retornamos um NULL. *

/ * Agora entramos em nosso loop para dividir nossa string fornecida. Nosso loop principal
continuará enquanto não atingirmos o final de nossa string de parâmetro. Dentro, temos outro

Libft 19
loop para passar por todos os caracteres do parâmetro c que existem. Isso vai parar quando
alcançarmos nosso primeiro caractere não c. Em seguida, definimos nossa variável j igual ao
valor de i neste ponto em nossa função. j será usado para apontar para a posição inicial do
índice de nossa primeira palavra dentro de nossa string s. Em seguida, continuamos nos
movendo através da string s, desde que não encontremos nosso caractere do parâmetro c.
Assim que fizermos isso, passamos para nossa instrução if. Se i for maior que j, o que deveria
ser se houver uma palavra que desejamos, colocaremos essa palavra na posição 0 do índice
de nossa tabela (que atualmente é o valor de k). Fazemos isso usando a função ft_strndup
acima e damos a ela dois parâmetros; Nossa string de parâmetro s (mas na posição de índice
de j, o início da palavra que queremos) e o tamanho / comprimento da palavra que
encontramos subtraindo o valor de j do valor de i (as posições de índice inicial e final da
nossa palavra). Em seguida, incrementamos k para mover para a próxima posição em nossa
mesa. Repetimos o loop while principal até chegarmos ao final de nossa string de parâmetro
s. Terminamos adicionando um NULL de terminação à nossa guia de tabela. Em seguida,
devolvemos nossa tabela pronta. * /

ft_itoa

Function name ft_itoa


Prototype char *ft_itoa(int n);
Turn in files -
Parameters
#1. the integer to convert.
Return value
The string representing the integer.
NULL if the allocation fails.
External functs. malloc
Description
Allocates (with malloc(3)) and returns a string
representing the integer received as an argument.
Negative numbers must be handled.

Esta função aloca memória e retorna uma string 'nova' de caracteres terminados com um '\ 0'
que é o equivalente em char do int passado no parâmetro. Números negativos também
devem ser gerenciados. Se a alocação falhar, a função retornará NULL. NOTA: Esta é uma
função recursiva. Se você não estiver familiarizado com funções recursivas, é uma função
que se auto-chama ou está em um ciclo potencial de chamadas de função. * /

Começamos criando uma variável de string char. É isso que nossa função retornará. Em
seguida, alocamos memória para nossa variável de string str. NOTA: Nós alocamos memória
apenas para um tamanho de 2 valores de char. Isso ocorre porque estaremos realizando essa
função de maneira indiscriminada e queremos alocar a memória apenas quando precisamos
dela. Fazemos um tamanho de 2 em nossa função malloc porque queremos fazer um
caractere por vez a partir do int n fornecido, um espaço para o número de um dígito
convertido em um caractere e o final '\ 0' que é necessário para terminar isso string individual
do char. Se a alocação falhar, retornamos NULL. Também queremos compensar a chance de
o int passado para nós ser o menor inteiro possível. Se recebermos esse número em nosso
parâmetro, nos certificamos de retornar uma string dele. * /

Libft 20
Em seguida, queremos ver se o int que é passado em nosso parâmetro é um número
negativo. Se int n for menor que zero, então tornamos a posição 0 do índice de nossa string
'fresca' um sinal negativo e a posição 1 uma terminação '\ 0'. Em seguida, definimos string str
igual a ft_strjoin com nosso str como parâmetro e chamamos recursivamente nossa função
com a -n de modo a transformar o int negativo em positivo. Em seguida, iniciamos a função
novamente.

Abaixo, estamos dizendo que se o int n passado em nosso parâmetro é maior que 10,
queremos quebrá-lo recursivamente para podermos construí-lo novamente como uma string.
Fazemos isso definindo nossa string alocada na memória str igual à nossa função ft_strjoin
criada anteriormente e passamos o parâmetro de nossa função ft_itoa com n dividido por 10 e
nossa função ft_itoa com n módulo 10. É aqui que a ideia de como funciona a recursão pode
ser difícil de entender. Este uso de ft_strjoin não acontecerá até mais tarde porque estamos
chamando ft_itoa novamente. Isso dividirá nosso int fornecido por 10 e pegará o resultado e
iniciará a função novamente, quebrando-o constantemente até que tenhamos o primeiro
número em nosso int. Por exemplo, se começarmos com o número n = 123, nossa chamada
de ft_itoa (n / 10) e ft_itoa (n% 10) é realmente ft_itoa (123/10) e ft_itoa (123% 10). Isso
chamará ft_itoa em um valor de 12 para a divisão por 10 e chamará ft_itoa no valor de 3 para
nosso módulo 10. É assim que dividimos o número em dígitos individuais. Para o nosso
resultado de 3, ele começará esta função novamente e pulará esta seção, pois agora será um
valor menor que 10. Vemos em nossa próxima instrução else if que se o número for maior
que 0 e menor que 10 nós converta-o aqui em uma string individual que seria "3 \ 0" porque
devemos ter uma terminação '\ 0'. Esta string individual será retornada para a função ft_strjoin
na qual foi chamada para ser unida à string que será retornada de seu parâmetro semelhante.
Mas o que aconteceu com o ft_itoa (123/10)? Bem, isso nos deu o número 12 para colocar
nesta função ft_itoa. Uma vez que este número ainda é maior que 10, usaremos a instrução if
que usará ft_strjoin com as duas funções ft_itoa passadas para seus parâmetros, mas desta
vez no valor de 12. Como aconteceu anteriormente com o valor total de 123, estaremos
dividindo este 12 agora em um individual 1 e 2. Executando ft_itoa em cada número
individual. Uma vez que ambos os números têm um valor menor que 10, mas maior que 0,
iremos convertê-los em uma string. Portanto, neste ponto agora temos as strings "1 \ 0", "2 \
0", e de nossa chamada anterior de ft_itoa (123% 10), temos a string "3 \ 0". Uma vez que
alcançamos um ponto final de retorno para nossa recursão, estaremos combinando primeiro
as strings "1 \ 0" e "2 \ 0" dentro da função ft_strjoin, elas estão atualmente dentro, tornando-
as na string "12 \ 0". Isso nos traz de volta um nível em nossa recursão para agora unir "12 \
0" com a string "3 \ 0" tornando a string "123 \ 0". Uma vez que isso foi colocado agora em
nossa string str (NOTA: temos alocado memória para cada string em cada chamada de ft_itoa
em nossa recursão), podemos retorná-lo agora que o número inteiro foi convertido em uma
string char. Terminando assim nossa função. Se isso tem sido difícil de imaginar em sua
cabeça, tente percorrer a função em um pedaço de papel. Ele deve se dividir como uma
espécie de árvore binária. * /

ft_strmapi

Function name ft_strmapi


Prototype char *ft_strmapi(char const *s, char (*f)(unsigned int, char));

Libft 21
Turn in files -
Parameters
#1. The string on which to iterate.
#2. The function to apply to each character.
Return value
The string created from the successive applications
of ’f’. Returns NULL if the allocation fails.
External functs. malloc
Description
Applies the function ’f’ to each character of the
string ’s’ to create a new string (with malloc(3))
resulting from successive applications of ’f’.

Nome da função ft_strmapi


Protótipo char * ft_strmapi (char const * s, char (* f) (unsigned int, char));
Entregar arquivos -
Parâmetros
1. A string na qual iterar.
2. A função a ser aplicada a cada personagem.
Valor de retorno
A string criada a partir das aplicações sucessivas
fora'. Retorna NULL se a alocação falhar.
Funções externas. Malloc
Descrição
Aplica a função 'f' a cada caractere do
string 's' para criar uma nova string (com malloc (3))
resultante de aplicações sucessivas de 'f'

ft_putchar_fd

Function name ft_putchar_fd


Prototype void ft_putchar_fd(char c, int fd);
Turn in files -
Parameters
#1. The character to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description
Outputs the character ’c’ to the given file descriptor.

Function name ft_putstr_fd


Prototype void ft_putstr_fd(char *s, int fd);
Turn in files -
Parameters
#1. The string to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the string ’s’ to the given file descriptor.

Function name ft_putendl_fd


Prototype void ft_putendl_fd(char *s, int fd);
Turn in files -
Parameters
#1. The string to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the string ’s’ to the given file descriptor,
followed by a newline.

Libft 22
Function name ft_putnbr_fd
Prototype void ft_putnbr_fd(int n, int fd);
Turn in files -
Parameters
#1. The integer to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description
Outputs the integer ’n’ to the given file descriptor.

ft_putchar_fd

Function name ft_putchar_fd


Prototype void ft_putchar_fd(char c, int fd);
Turn in files -
Parameters #1. The character to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the character ’c’ to the given file
descriptor.

Function name ft_putstr_fd


Prototype void ft_putstr_fd(char *s, int fd);
Turn in files -
Parameters #1. The string to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the string ’s’ to the given file
descriptor.

Function name ft_putendl_fd


Prototype void ft_putendl_fd(char *s, int fd);
Turn in files -
Parameters #1. The string to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the string ’s’ to the given file
descriptor, followed by a newline.

Function name ft_putnbr_fd


Prototype void ft_putnbr_fd(int n, int fd);
Turn in files -
Parameters #1. The integer to output.
#2. The file descriptor on which to write.
Return value None
External functs. write
Description Outputs the integer ’n’ to the given file
descriptor.

ft_lstnew

Function name ft_lstnew


Prototype t_list *ft_lstnew(void *content);
Turn in files -
Parameters
#1. The content to create the new element with.
Return value
The new element.

Libft 23
External functs. malloc
Description
Allocates (with malloc(3)) and returns a new
element. The variable ’content’ is initialized
with the value of the parameter ’content’. The
variable ’next’ is initialized to NULL.

Function name ft_lstadd_front


Prototype void ft_lstadd_front(t_list **lst, t_list *new);
Turn in files -
Parameters
#1. The address of a pointer to the first link of a list.
#2. The address of a pointer to the element to be added to the list.
Return value
None
External functs. None
Description
Adds the element ’new’ at the beginning of the list.

Function name ft_lstsize


Prototype int ft_lstsize(t_list *lst);
Turn in files -
Parameters
#1. The beginning of the list.
Return value
Length of the list.
External functs. None
Description
Counts the number of elements in a list.

Function name ft_lstlast


Prototype t_list *ft_lstlast(t_list *lst);
Turn in files -
Parameters
#1. The beginning of the list.
Return value
Last element of the list.
External functs. None
Description
Returns the last element of the list.

Function name ft_lstadd_back


Prototype void ft_lstadd_back(t_list **lst, t_list *new);
Turn in files -
Parameters
#1. The address of a pointer to the first link of a list.
#2. The address of a pointer to the element to be added to the list.
Return value
None
External functs. None
Description
Adds the element ’new’ at the end of the list.

Function name ft_lstdelone


Prototype void ft_lstdelone(t_list *lst, void (*del)(void*));
Turn in files -
Parameters
#1. The element to free.
#2. The address of the function used to delete the content.
Return value None
External functs. free
Description
Takes as a parameter an element and frees the
memory of the element’s content using the function
’del’ given as a parameter and free the element.
The memory of ’next’ must not be freed.

Libft 24
Function name ft_lstclear
Prototype void ft_lstclear(t_list **lst, void (*del)(void*));
Turn in files -
Parameters
#1. The adress of a pointer to an element.
#2. The adress of the function used to delete the content of the element.
Return value
None
External functs. free
Description
Deletes and frees the given element and every successor of that element,
using the function ’del’ and free(3).
Finally, the pointer to the list must be set to NULL.

Function name ft_lstiter


Prototype void ft_lstiter(t_list *lst, void (*f)(void *));
Turn in files -
Parameters
#1. The adress of a pointer to an element.
#2. The adress of the function used to iterate on the list.
Return value
None
External functs. None
Description
Iterates the list ’lst’ and applies the function ’f’ to the content of each element.

Function name ft_lstmap


Prototype t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *));
Turn in files -
Parameters
#1. The adress of a pointer to an element.
#2. The adress of the function used to iterate on the list.
#3. The adress of the function used to delete the content of an element if needed.
Return value
The new list. NULL if the allocation fails.
External functs. malloc, free
Description
Iterates the list ’lst’ and applies the function ’f’ to the content of each element.
Creates a new list resulting of the successive applications of the function ’f’.
The ’del’ function is used to delete the content of an element if needed.

Chinimala/42-tests
To test 42 exercises. Contribute to Chinimala/42-tests development by creating
an account on GitHub.

https://github.com/Chinimala/42-tests/blob/master/test-libft.c

Understanding and implementing


C Programming
a Linked ListTutorials
in C and Java
Static vs. Shared Librari
https://www.youtube.co Understanding and implementingOfficial
a Linked
playlist
List inforC and Java // Static vs. Shared
m/playlist?list=PL78280 Linked lists are one of the most fundamental
thenewbostondataC structures that any
LibrariesInstagram:
D6BE6F05D34 computer programmer nee... Programming Tutorials! https://instagram.com/dave
https://www.youtube.com/watch?v=VOpjAHCee7c&t=1s
https://www.youtube.co https://www.youtube.co
m/playlist?list=PL6gx4Cwl9 watch?v=-vp9cFQCQCo&a
DGAKIXv8Yr6nhGJ9Vlcjyy channel=DaveXiang
mq

Libft 25
Structs aninhadas e vetor de struct em C Struct Linguagem C
Neste vídeo veremos como construir structs Veja como utilizar struct ,
aninhadas e como trabalhar com vetor de declarando e recebendo
struct em linguagem C. dados em um programa
https://www.youtube.com/watch?v=h0GL9 https://www.youtube.c
vWcxB8 om/watch?v=Lktyz-vojCQ

Libft 26

Você também pode gostar