char *strdup(char *src)
strdup은 문자열 src를 복사하기 위해 메모리를 할당하고 (malloc 사용), 그곳에 src를 복사한다. 그리고 그 만들어진 문자열 포인터가 가르키는 곳을 반환한다.
1.우선 src의 길이를 재고 null 자리를 포함하여 동적할당 진행.
#include<stdio.h>
ex00
#include<stdlib.h>
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
i++;
}
return (i);
}
char *ft_strdup(char *src)
{
char *new_src;
int i;
i = ft_strlen(src);
new_src = (char *)malloc(sizeof(char) * (i + 1));
if (!(new_src))
return (NULL);
i = 0;
while (src[i])
{
new_src[i] = src[i];
i++;
}
new_src[i] = '\0';
return (new_src);
}
ex01
#include<stdlib.h>
int *ft_range(int min, int max)
{
int *result;
int i;
if (max <= min)
return (NULL);
result = (int *) malloc(sizeof(int) * (max - min));
if (!(result))
return (NULL);
i = 0;
while (min < max)
{
result[i] = min;
i++;
min++;
}
return (result);
}
#include <stdio.h>
int main()
{
int a = 2147483647;
int b = 0;
printf("값은 %d입니다", *ft_range(b, a));
return (0);
}
ex02
#include<stdlib.h>
int ft_ultimate_range(int **range, int min, int max)
{
int *result;
int i;
i = max - min;
if (i <= 0)
return (0);
result = (int *)malloc(sizeof(int *) * (max - min));
if (!(result))
return (-1);
i = 0;
while (min < max)
{
result[i] = min ++;
i++;
}
*range = result;
return (i);
}
ex03