【问题标题】:How to store char pointers in Arduino to a variable如何将 Arduino 中的字符指针存储到变量中
【发布时间】:2021-03-18 19:05:11
【问题描述】:

这是我正在实现的代码。我正在使用 arduino 进行编程。这是天蓝色云示例的一部分。

static void DeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad, int size)
{

  char *temp = (char *)malloc(size + 1);
  if (temp == NULL)
  {
    return;
  }
  receivedDesired = true;
  memcpy(temp, payLoad, size);
  temp[size] = '\0';
  // Display Twin message.

  Serial.println("This is temp");
  Serial.println(temp);  
  free(temp);
}

当我调用这个函数时,一切正常,temp 变量被打印出来。但我想将 temp 中的值分配给字符串变量。我该怎么做。我对指针知之甚少。提前致谢。

【问题讨论】:

  • 不要在 C++ 中使用malloc
  • 您使用什么语言? CC++ 是不一样的,并且会导致如何解决您的问题的不同建议。对于任何一种语言,请包含minimal reproducible example
  • 对此感到抱歉。我正在使用 arduino 代码
  • 不要在像arduino这样的微型嵌入式系统中使用动态分配[
  • 能否给我一个代码作为解释。那真的很有帮助。谢谢

标签: c++ string pointers arduino-c++


【解决方案1】:

使用std::string,在其Arduino 伪装中称为String,假设payLoad 是在调用函数之前以\0 终止的CString:

static void DeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad) {
  String temp(payLoad);
  receivedDesired = true;

  // Display Twin message.
  Serial.println("This is temp: ");
  Serial.println(temp);  
}

如果 payLoad 不是 CString,但具有已知大小(注意 std::string::string(const char* s, size_t n) 在 Arduino 的 String 实现中似乎不存在):

static void DeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad, int size) {
  String temp;
  for (int i=0; i<size; i++) {
    temp += payload[i];
  }
  receivedDesired = true;

  // Display Twin message.
  Serial.println("This is temp: ");
  Serial.println(temp);  
}

在这两个例子中,temp 现在是一个String 对象;我希望这就是你想要的。

注意String 也进行动态内存分配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多