0

I have a function that does some reallocating like this:

void str_replace(char** str, const char* a, const char* b)
{
    *str = realloc(*str, 100);
}

and I call that function in main using:

char test[] = "some test string";
str_replace(&test, "test", "tested");

But gcc throws a warning:

../main/app_main.c: In function 'app_main':
../main/app_main.c:567:17: warning: passing argument 1 of 'str_replace' from incompatible pointer type [-Wincompatible-pointer-types]
     str_replace(&test, "test", "tested");
                 ^~~~~
../main/app_main.c:186:30: note: expected 'char **' but argument is of type 'char (*)[17]'
 esp_err_t str_replace(char **str_to_replace, const char *old, const char *new)

Two questions:

  • How do I convert an object of type char (*)[n] to char**?
  • I'm trying to realloc a stack allocated object. Is this even allowed?
glades
  • 3,778
  • 1
  • 12
  • 34
  • The `**char` should be `char **`. Also `str_replace` should be `void str_replace`. You cannot reallocate constant literals. You should replace `char test[] =` with `char *test = malloc(...)`. – DaBler Aug 12 '21 at 09:30
  • @DaBler: Thanks! I edited the question as the first two issues are mistakes I made. So it has to be dynamically allocated then? I thought that even pointers to constant literals would decay. – glades Aug 12 '21 at 09:33
  • You can assign constant literal into `char *`. However, you program then crashes with `realloc(): invalid pointer` as the constant literal was not allocated with `malloc()` and it is invalid to pass such a pointer to `free()`. – DaBler Aug 12 '21 at 10:39

0 Answers0