Dynamically Allocate Memory For An Array Of Chars

I'm trying to create dynamic array of strings, but obviously I'm missing something... This does not compile:

char **AOC;
AOC = malloc(20 * sizeof(char *));
AOC[0] = malloc(20 * sizeof(char));

with this error:

AOC = malloc(20 * sizeof(char *));
^
error: 'AOC' does not name a type

exit status 1

Compilation error: 'AOC' does not name a type

Please, point me the right way.

It depends on where those statements are located in your sketch. It is always best to post a complete sketch that others can copy/compile.

If those statements are inside setup() or loop(), the code compiles just fine. If they are at the global level (e.g. outside any function) then you get that error. C++ doesn't allow arbitrary code outside a function. You can declare your variable at a global scope, but the malloc() calls need to be within a function, such as setup()

char **AOC;

void setup()
{
AOC = malloc(20 * sizeof(char *));
AOC[0] = malloc(20 * sizeof(char));
}

void loop()
{
  //do nothing
}
1 Like

I see! Yes, I had it on the global level.

But, even that it is not compiling :wink: When I try the code you posted, I get this error:

C:\sketch_dec29b.ino: In function 'void setup()':
C:\sketch_dec29b.ino:5:13: error: invalid conversion from 'void*' to 'char**' [-fpermissive]
 AOC = malloc(20 * sizeof(char *));
             ^
C:\sketch_dec29b.ino:6:16: error: invalid conversion from 'void*' to 'char*' [-fpermissive]
 AOC[0] = malloc(20 * sizeof(char));
                ^

exit status 1

Compilation error: invalid conversion from 'void*' to 'char**' [-fpermissive]

Cpp Core Guidelines: Don't use malloc and free

1 Like

Seems like this does the trick. Need to verify if it does what I expect. And I have to study the previously posted link. Thanks!

char **AOC;

void setup()
{
AOC = (char**) malloc(20 * sizeof(char *));
AOC[0] = (char*) malloc(20 * sizeof(char));
}

void loop()
{
//do nothing
}

Are you sure you need a dynamic array? If so, you may be better off using a vector instead.

If you have access to the standard template library, you can use std::vector, otherwise some stand alone libraries are available.

You could make a char[20] or String vector for example.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.