Reputation: 13345
This code
#include "alloca.h"
String str = "abc";
unsigned int *i;
void setup() {
Serial.begin(9600);
i = alloca(StringLength() * sizeof(i));
unsigned int j[StringLength() * sizeof(i)];
}
int StringLength() {
return str.length();
}
void loop() {
}
gives me the following error messages:
sketch_dec11f.cpp: In function ‘void setup()’: sketch_dec11f.cpp:14:7: error: invalid conversion from ‘void*’ to ‘unsigned int*’
What am I doing wrong?
(tried it with malloc() as well, also didn't work!)
Upvotes: 1
Views: 288
Reputation: 477434
In C++, void pointers are not implicitly convertible to other pointers, unlike in C. Therefore you need a cast:
i = static_cast<unsigned int *>(alloca(StringLength() * sizeof(i)));
Upvotes: 1
Reputation: 21233
Cast the returning pointer from alloca:
i = (unsigned int *) alloca(StringLength() * sizeof(i));
Upvotes: 1
Reputation: 63767
I am not sure of alloca, but malloc return's void * and C++ unlike C doesn't support implicit conversion from void * to any other pointer type. This is one of the many areas where C++ differs from C.
Upvotes: 1
Reputation: 93880
You definitely don't want alloca()
. That's an allocation that is on the stack of the function and only lasts for the duration of the call. It lets you have dynamic arrays that go away on function return (in C++ you could do this with RAII, but in C alloca
was the only way).
You just need a cast in your allocation. Try i = (unsigned int *)malloc(StringLength() * sizeof(*i))
. Note the sizeof(*i)
. That's the size of one member: sizeof(i)
is the size of the pointer and is not likely to be related to what's inside.
Upvotes: 2
Reputation: 15110
Malloc and alloca return void * pointers. Just change
i = alloca(StringLength() * sizeof(i));
to
i = (unsigned int *)alloca(StringLength() * sizeof(i));
Upvotes: 1