Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language : string concatenation on string pointer

Tags:

c

I have code this add_str function :

void    add_str(char *str1, char *str2, char **res)
{
  int   i;
  int   j = 0;

  res[0] = malloc((strlen(str1) + strlen(str2) + 1) * sizeof(char));
  if (res[0] == NULL)
    return;
  for (i = 0; str1[i]; i++)
    res[0][j++] = str1[i];
  for (i = 0; str2[i]; i++)
    res[0][j++] = str2[i];
  res[0][j] = '\0';
}

It receives 2 strings, str1 and str2 and a pointer an string **res which is not malloc. My function add str1 and str2 on **res.

My question is : Is there a way to do not write res[0] each time I have to do something with it ?

like image 250
Jérémy Pouyet Avatar asked Dec 11 '22 08:12

Jérémy Pouyet


2 Answers

res is a pointer to a pointer, so you need to dereference it before you use it. You're right that res[0] isn't the right way to do that though in this context. Use (*res) instead.

like image 81
Peter Bloomfield Avatar answered Dec 27 '22 02:12

Peter Bloomfield


What you really want is to dereference:

*res
like image 35
EricSchaefer Avatar answered Dec 27 '22 03:12

EricSchaefer