【问题标题】:Concatenate two char pointers with unknown sizes without using strings in arduino在arduino中不使用字符串连接两个大小未知的字符指针
【发布时间】:2021-04-26 05:41:31
【问题描述】:

首先,让我告诉你为什么我不能使用字符串——因为我的数据长度超过了 2048 字节

一个简化的代码是这样的

char* pointerOne = "First part";
char* pointerTwo = "Seconds part";

我需要连接pointerOne 和poniterTwo。 pointerOne 和pointerTwo 的长度发生变化。 有没有办法在不硬编码长度的情况下获得单个字符数组? 我可以灵活地更改为任何数据类型。 我尝试使用 JSON 数据类型,它可以工作,但对于我所需的数据速率来说太慢了。

谢谢。

【问题讨论】:

  • 获取字符串的长度,并分配length_of_first + lenght_of_second + 1字节来存储结果字符串?哦,Arduino 通常是用 C++ 编程的,而不是 C。
  • 这是你想要的吗? char* str = malloc(strlen(pointerOne) + strlen(pointerTwo) + 1), strcpy(str, pointerOne); strcat(pointerOne, pointerTwo);
  • 您不能连接指针。您要做的是连接字符串。 size_t newlen = strlen(pointerOne) + strlen(pointerTwo); char *newstr = malloc(newlen+1); if (newstr) sprintf(newstr, "%s%s", pointerOne, pointerTwo);
  • char* pointerOne = "First part"; 应该是const char* pointerOne = "First part";

标签: c++ arrays pointers arduino


【解决方案1】:

由于长度不同,您必须使用动态内存和 realloc() (https://riptutorial.com/c/example/4329/reallocating-memory) 来连接字符数组,使用 memcpy() 将第二部分连接到第一部分(之后(重新)分配足够的内存,https://en.cppreference.com/w/cpp/string/byte/memcpyhttps://www.tutorialspoint.com/c_standard_library/c_function_memcpy.htm

标记值可用于确定有效数据的长度(即第一部分和第二部分结束的位置)

https://en.wikipedia.org/wiki/Sentinel_value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2015-06-18
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多