chupito
December 29, 2022, 7:45pm
1
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.
blh64
December 29, 2022, 7:53pm
2
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
chupito
December 29, 2022, 7:59pm
3
I see! Yes, I had it on the global level.
But, even that it is not compiling 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]
PieterP
December 29, 2022, 8:05pm
4
1 Like
chupito
December 29, 2022, 8:09pm
5
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.
The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.
You could make a char[20]
or String
vector for example.
1 Like
system
Closed
June 27, 2023, 8:23pm
7
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.