[英]How to pass string by reference in Arduino C++
我是 Arduino 的新手,近十年來沒有做過任何 C++。 所以這是我真正基本的問題:
我想制作一個可以返回兩個字符串的 function,因為我正在考慮通過引用傳遞字符串。 像這樣的東西:
void return_array_byref((char[]) & device, (char[]) & command)
{
device = malloc(8 * sizeof(char));
device[0] = 'C';
device[1] = '\n';
command= malloc(8 * sizeof(char));
command[0] = 'C';
command[1] = '\n';
}
void loop() {
char * device;
char * command;
return_array_byref(device, command);
...
}
我曾嘗試使用char **
、 char[] &
、 char * &
但似乎沒有任何效果。 通過上面的代碼,我得到了這個:
arduino:6:25: error: variable or field 'return_array_byref' declared void
void return_array_byref((char[]) & device)
^
在 C++ 中這樣做的正確方法是什么?
[編輯][解決方案]
這是我正在尋找的代碼。 我根據下面提供的答案得出了這個解決方案,所以功勞歸於@Doncho :)
void return_array_byref(char * * device)
{
*device = (char*) malloc(sizeof(char) * 8); // allocate the size of the pointer array
(*device)[0] = 'A';
(*device)[1] = 'B';
(*device)[2] = 'C';
(*device)[3] = '\n'; // this is just a new line, does not end the string
(*device)[4] = '\0'; // null terminator is important!
}
void main()
{
char * string;
return_array_byref(&string);
cout << string << endl;
free(string);
}
我會避免傳遞字符串的數組作為參考。 使用 C 的強大功能,將指針傳遞給您將動態分配的數組。
下面的代碼就是這樣做的:它接收一個指向 C 字符串數組的指針。 然后它首先分配數組 (sizeof(char *) * count) 個元素,然后分配該數組中的每個字符串並分配一個值。 如果你想要真正的 C 風格的字符串,你需要用 '\0' 結束它,而不是 '\n'。
我沒有我的 Arduino 設置了,但代碼應該是這樣的:
void return_array_byref(char * * device, unsinged count)
{
*device = malloc(sizeof(char *)*count); // allocate the size of the pointer array
int i;
for(i=0; i<count; i++) {
device[i] = malloc(sizeof(char)*10); // just for the example, allocate 9 char length string
device[i][0] = 'A'+i;
device[i][1] = '\n'; // this is just a new line, does not end the string
device[i][2] = '\0'; // null terminator is important!
}
}
// the loop routine runs over and over again forever:
void loop() {
char ** string; // bear in mind this is just ONE string, not two
return_array_byref_string(string);
// bear in mind, somewhere in your code you need to free up the memory!
// free up each of the strings:
// for(int i=0; i<count; i++) free(string[i]); // free up the strings allocation
// free(string); // free up the strigs array array
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.