我需要 malloc C 风格的字符串吗?
Do I need to malloc C-style strings?
我最近开始使用Arduino,所以我仍然需要适应并找到C/C++和Arduino语言之间的差异。
所以我有一个问题要问你。
当我看到有人在 Arduino (char *str
) 中使用 C 风格的字符串时,他们总是像这样初始化它(并且从不释放它):
char *str = "Hello World";
在纯 C 中,我会做这样的事情:
int my_strlen(char const *str)
{
int i = 0;
while (str[i]) {
i++;
}
return (i);
}
char *my_strcpy(char *dest, char const *src)
{
char *it = dest;
while (*src != 0) {
*it = *src;
it++;
src++;
}
return (dest);
}
char *my_strdup(char const *s)
{
char *result = NULL;
int length = my_strlen(s);
result = my_malloc(sizeof(char const) * (length + 1));
if (result == NULL) {
return (NULL);
}
my_strcpy(result, s);
return (result);
}
然后像这样初始化它:
char *str = my_strdup("Hello World");
my_free(str);
所以这是我的问题,关于 C 风格的 Arduino 字符串,malloc 是可选的还是这些人搞错了?
感谢您的回答。
在 C++ 中,最好使用 new[]
/delete[]
而不要将其与 malloc
/free
.
混合使用
在 Arduino 中还有字符串 class,它对您隐藏了这些分配。
然而,在这种受限制的平台上使用动态内存分配有其缺陷,如堆碎片(主要是因为 String 重载 + 运算符,所以每个人都过度使用它,如:Serial.println(String{"something : "} + a + b + c + d + ......)
然后想知道神秘的崩溃。
有关 Majenko 博客的更多信息:The Evils of Arduino String class(Majenko 在 arduino stackexchange 上的声誉最高)
基本上使用字符串 class 你的 strdup 代码会很简单:
String str{"Hello World"};
String copyOfStr = str;
我最近开始使用Arduino,所以我仍然需要适应并找到C/C++和Arduino语言之间的差异。
所以我有一个问题要问你。
当我看到有人在 Arduino (char *str
) 中使用 C 风格的字符串时,他们总是像这样初始化它(并且从不释放它):
char *str = "Hello World";
在纯 C 中,我会做这样的事情:
int my_strlen(char const *str)
{
int i = 0;
while (str[i]) {
i++;
}
return (i);
}
char *my_strcpy(char *dest, char const *src)
{
char *it = dest;
while (*src != 0) {
*it = *src;
it++;
src++;
}
return (dest);
}
char *my_strdup(char const *s)
{
char *result = NULL;
int length = my_strlen(s);
result = my_malloc(sizeof(char const) * (length + 1));
if (result == NULL) {
return (NULL);
}
my_strcpy(result, s);
return (result);
}
然后像这样初始化它:
char *str = my_strdup("Hello World");
my_free(str);
所以这是我的问题,关于 C 风格的 Arduino 字符串,malloc 是可选的还是这些人搞错了?
感谢您的回答。
在 C++ 中,最好使用 new[]
/delete[]
而不要将其与 malloc
/free
.
在 Arduino 中还有字符串 class,它对您隐藏了这些分配。
然而,在这种受限制的平台上使用动态内存分配有其缺陷,如堆碎片(主要是因为 String 重载 + 运算符,所以每个人都过度使用它,如:Serial.println(String{"something : "} + a + b + c + d + ......)
然后想知道神秘的崩溃。
有关 Majenko 博客的更多信息:The Evils of Arduino String class(Majenko 在 arduino stackexchange 上的声誉最高)
基本上使用字符串 class 你的 strdup 代码会很简单:
String str{"Hello World"};
String copyOfStr = str;