I'm trying to count the elements of the array's arrays for the allocation of memory "res," used to concatenate, including NULL terminators, every string stored in "argv". There are probably more bugs to be found, but the first I don't understand is argv[a][b] != NULL
in /* length of arrays */
. Why isn't this acceptable and are there other ways --without hardcoding- or passing length-- to determine number of elements?
used: http://pythontutor.com/c.html#mode=edit
char *ft_concat_params (int argc, char **argv)
{
int len_argc = argc - 1,
len_argv = 0;
char *res = NULL;
/* length of argvs */
for (int a = 0; a < len_argc; a++) {
for (int b = 0;argv[a][b] != NULL; b++) {
len_argv++;
}
}
/* allocate memory res -- freed by calling function! */
res = malloc (len_argv * sizeof * res);
if (!res) {
ft_putstr ("not allocated res");
free(res);
return NULL;
}
/* concate strings */
for (int a = 0; a < len_argc; a++) {
int b = 0;
while (argv[a][b] != '\0') {
res = &argv[a][b];
b++;
}
res[b] = '\0';
}
return res;
}
int main(void)
{
int argc = 4;
char argv[3][6] = {
{'s','t','a','r','t','\0'},
{'s','t','a','r','t','\0'},
{'s','t','a','r','t','\0'}
};
char *arr;
arr = ft_concat_params (argc, argv);
if (!arr) /* validate return */
return 1;
free(arr);
}