c++ - 使用 alloca 分配内存时转换无效

标签 c++ arduino

这段代码

#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() {
}

给我以下错误信息:

sketch_dec11f.cpp: In function ‘void setup()’: sketch_dec11f.cpp:14:7: error: invalid conversion from ‘void*’ to ‘unsigned int*’

我做错了什么?

(也用 malloc() 试过了,也没用!)

最佳答案

您绝对不需要 alloca()。这是函数堆栈上的分配,仅在调用期间持续。它允许您拥有在函数返回时消失的动态数组(在 C++ 中,您可以使用 RAII 执行此操作,但在 C 中,alloca 是唯一的方法)。

您只需要在您的分配中进行强制转换。试试 i = (unsigned int *)malloc(StringLength() * sizeof(*i))。注意 sizeof(*i)。那是一个成员的大小:sizeof(i) 是指针的大小,不太可能与里面的内容有关。

关于c++ - 使用 alloca 分配内存时转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467009/

相关文章:

c++ - 使用 NeoPixels 的 Arduino 功能无法正确循环

c++ - 如何获得可用的加速度计读数

c++ - VB.NET 无法加载 DLL 找不到指定的模块。当dll导入时

c++ - C++ 中的全局字符串数组

c++ - 在apache2上配置cgi

c++ - 什么是 "cerr"和 "stderr"?

android - 蓝牙串口通讯,HC-06模块转安卓手机

hardware - AVR 和 Arduino 之间有什么区别/关系?

c++ - 如何在 OS X 上的 Qt 应用程序中设置应用程序图标,足以分发?

c - 将类型定义的二维结构数组作为函数参数传递