diff --git a/0x0B-malloc_free/100-argstostr.c b/0x0B-malloc_free/100-argstostr.c index 72d8d61..5abcbd2 100644 --- a/0x0B-malloc_free/100-argstostr.c +++ b/0x0B-malloc_free/100-argstostr.c @@ -1,45 +1,52 @@ -#include #include "main.h" +#include /** - * *argstostr - concatenates all the arguments of the program - * @ac: number of arguments - * @av: array of arguments + * argstostr - concatenates all the arguments of a program. + * @ac: argument count. + * @av: argument vector. * - * Return: Pointer to the new string (Success), NULL (Error) + * Return: pointer of an array of char */ char *argstostr(int ac, char **av) { - int i, j, k, len; - char *str; + char *aout; + int c, i, j, ia; - if (ac == 0 || av == NULL) + if (ac == 0) return (NULL); - for (i = 0; i < ac; i++) + for (c = i = 0; i < ac; i++) { + if (av[i] == NULL) + return (NULL); + for (j = 0; av[i][j] != '\0'; j++) - len++; - len++; + c++; + c++; } - str = malloc(sizeof(char) * (len + 1)); + aout = malloc((c + 1) * sizeof(char)); - if (str == NULL) + if (aout == NULL) + { + free(aout); return (NULL); + } - k = 0; - - for (i = 0; i < ac; i++) + for (i = j = ia = 0; ia < c; j++, ia++) { - for (j = 0; av[i][j] != '\0'; j++) + if (av[i][j] == '\0') { - str[k] = av[i][j]; - k++; + aout[ia] = '\n'; + i++; + ia++; + j = 0; } - str[k] = '\n'; - k++; + if (ia < c - 1) + aout[ia] = av[i][j]; } + aout[ia] = '\0'; - return (str); + return (aout); } diff --git a/0x0B-malloc_free/101-strstow.c b/0x0B-malloc_free/101-strstow.c new file mode 100644 index 0000000..4b48941 --- /dev/null +++ b/0x0B-malloc_free/101-strstow.c @@ -0,0 +1,67 @@ +#include "main.h" +#include + +/** + * ch_free_grid - frees a 2 dimensional array. + * @grid: multidimensional array of char. + * @height: height of the array. + * + * Return: no return + */ +void ch_free_grid(char **grid, unsigned int height) +{ + if (grid != NULL && height != 0) + { + for (; height > 0; height--) + free(grid[height]); + free(grid[height]); + free(grid); + } +} + +/** + * strtow - splits a string into words. + * @str: string. + * + * Return: pointer of an array of integers + */ +char **strtow(char *str) +{ + char **aout; + unsigned int c, height, i, j, a1; + + if (str == NULL || *str == '\0') + return (NULL); + for (c = height = 0; str[c] != '\0'; c++) + if (str[c] != ' ' && (str[c + 1] == ' ' || str[c + 1] == '\0')) + height++; + aout = malloc((height + 1) * sizeof(char *)); + if (aout == NULL || height == 0) + { + free(aout); + return (NULL); + } + for (i = a1 = 0; i < height; i++) + { + for (c = a1; str[c] != '\0'; c++) + { + if (str[c] == ' ') + a1++; + if (str[c] != ' ' && (str[c + 1] == ' ' || str[c + 1] == '\0')) + { + aout[i] = malloc((c - a1 + 2) * sizeof(char)); + if (aout[i] == NULL) + { + ch_free_grid(aout, i); + return (NULL); + } + break; + } + } + for (j = 0; a1 <= c; a1++, j++) + aout[i][j] = str[a1]; + aout[i][j] = '\0'; + } + aout[i] = NULL; + return (aout); +}