我正在用 C 语言对 Arduino 板进行编程,因此除非与外部终端窗口进行串行通信,否则无法打印。
因此我开发了一个 printAll 方法:
void printAll(char * str) {
int i;
for(i = 0; str[i] != 0x00; i++) {
PSerial_write('0', str[i]);
}
}
我还有一个变量:
char input[12];
input[0] = 'h';
input[1] = 'e';
input[2] = 'l';
input[3] = 'p';
我想做的是将这个数组传递到 printAll 方法中(但 printAll 方法需要一个 char*)。
我尝试过:
printAll(&input[0]);
但是什么也没有打印出来!但是当我单步执行并打印输入数组的每个字符时,我得到:
help<0><0><0><0><0><0><0><0>
谁能解释一下为什么这不起作用?谢谢!
***注意: printAll 方法在像这样使用时工作得很好:
printAll("Hello World!");
总的来说,我的代码如下所示:
char input[12];
int main(void) {
start();
}
void start() {
while(1) {
printAll("Please enter in a command!\r");
printAll("Please type 'help' for instructions!\r");
char input[12];
readInput(input);
printAll("Trying to print the char array stuff....\r");
printAll(input);
if (input == "help") printHelp();
else if (input == "set") {
if (setStatus) printSet();
else printAll("Controller not authorized to print.\n");
}
else if (input == "set on") setStatus = true;
else if (input == "set off") setStatus = false;
else if (input == "set hex=on") hexFormat = true;
else if (input == "set hex=off") hexFormat = false;
else if (input == "set tlow") tlow = getNumber(input);
else if (input == "set thigh") thigh = getNumber(input);
else if (input == "set period") period = getNumber(input);
x_yield();
}
}
void readInput() {
char c = PSerial_read('0'); //reads character from user
while (c != '\r') {
//while the character isnt 'enter'
input[currIndex] = c;
c = PSerial_read('0');
currIndex++;
}
int y;
for(y = 0; y < 12; y++) {
PSerial_write('0', input[y]);
//go through input and print each character
}
PSerial_write('0', '\r');
//add new line to print log
currIndex = 0; //reset for next input (overwrites current stuff)
}
现在无论我输入什么,它只是要求更多输入,并且在输入法返回后不会打印出数组。
最佳答案
您发送的代码是混合的,无法编译。该代码表明您有两个输入变量,一个全局变量,一个局部变量。 readInput() 读取全局值,而 printAll() 读取本地值(反之亦然,具体取决于更改的代码)。删除无论如何都不应该使用的全局输入,并将相同的输入变量传递给 readInput() 和 printAll()。
关于c - 如何在c中从char*访问char[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553797/