简体   繁体   English

如何将多个char *数组放入二维数组中?

[英]How do I put a number of char* arrays into a two dimensional array?

I have a char array char *menu_strings[8]; 我有一个char数组char *menu_strings[8]; that I fill with the options for an on-screen menu dynamically in a reusable menu() function. 我在可重用的menu()函数中动态填充了屏幕菜单的选项。 I can change the items individually with hand-typed strings, eg menu_strings[0] = "New"; 我可以使用手工键入的字符串分别更改项目,例如menu_strings[0] = "New"; etc. but how do I take a char* returned from another function and insert it into one of the array's "strings"? 等等,但是我如何从另一个函数返回一个char *并将其插入到数组的“字符串”之一中呢? If I try to loop through the array using the function with something like this: 如果我尝试使用带有以下功能的函数遍历数组:

for (i=0; i<8; i++)
{
  char returnedOption[32];
  if (getOption(i, returnedOption))
    menu_strings[i] = returnedOption;
}

bool getOption(byte entryNum, char* option) {  //code and stuff  }

...all 8 menu_strings are filled with the eighth/last option returned (i=7) instead of each individual entry's string... ...所有8个menu_strings都填充有返回的第八个/最后一个选项(i = 7),而不是每个单独条目的字符串...

for (i=0; i<8; i++)
  Serial.println(menu_strings[i]);

Outputs: 输出:

option eight
option eight
option eight
option eight
option eight
option eight
option eight
option eight

I'm using the arduino IDE but feel pretty confidently that I'd be screwing up the usage of pointers in any C/++/# here. 我使用的是arduino IDE,但是我很自信可以在这里使用任何C / ++ /#中的指针。 Also, the returned char* is never more than 31 chars plus a null pointer. 同样,返回的char *永远不能超过31个char加一个空指针。

Many thanks to PaulMcKenzie, yardpenalty and deviantfan who led me to the answer: 非常感谢PaulMcKenzie,四处惩罚和虔诚的粉丝,这些使我得到了答案:

Get out of the char * business and simply use std::string . 摆脱char *业务,只需使用std::string You are also probably returning the address of a local array, given what you posted. 给定您发布的内容,您可能还返回了本地数组的地址。 If you are doing that, returning the address of a local variable is undefined behavior. 如果这样做,则返回局部变量的地址是未定义的行为。

This led me to use the Arduino String object instead of char* https://www.arduino.cc/en/Reference/StringObject and use toCharArray() for any library calls that insist on a char pointer. 这导致我使用Arduino String对象而不是char* https://www.arduino.cc/zh-CN/Reference/StringObject,并且将toCharArray()用于所有坚持使用char指针的库调用。 This works, but added around 2k (or 7% of my usable program memory!). 这可行,但是增加了大约2k(或我可用程序内存的7%!)。

In the end, I ditched the * pointer as this is incorrect, and used strcpy properly as recommended by deviantfan and yardpenalty to stay away from the String library. 最后,我放弃了*指针,因为这是不正确的,并按照deviantfan和yardpenalty的建议正确使用了strcpy来远离String库。 Its liabilities are further extolled here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/ 它的责任在这里进一步受到重视: https : //hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM