我是 C 语言的新手(我正在使用 Delphi/pascal)并尝试获取一些温度传感器值并使它们大小相等/固定以发送到 MCU(使用 Arduino IDE - 所以我必须使用 C ).
数据长度 (strlen()) 可以是 3(如 5.3、0.9、0.0 等)、4(如 -4.2、19.8 等)或 5(如 -15.6),具体取决于温度传感器和以下代码;
char value[5]; // must be char in order to send to MCU
if ((temp_data>=temp_max){
fix_size(value,true); //Error part. writes: "EEEEE" to reach fix size: 5
} else {
dtostrf(temp_data, 0, 1, value);
fix_size(value,false); //I'll use this to send data to screen later..
}
我需要固定数据的大小(为此,我尝试在末尾添加零)并且我尝试在下面进行操作;
char fix_size(char temp_char[5],bool err=false){
if(err){
temp_char= "EEEEE";
Serial.println(temp_char);
return temp_char;
}
int num = strlen(temp_char);
// If strlen is 5 then it is OK and strlen cannot be 2 and 1 because of my temp sensor data processing (dtostrf(temp_data, 0, 1, value)) so I only need to take care 3 and 4
switch (num) {
case 3:
temp_char[3] = "0";
temp_char[4] = "\0";
//0.0 would become 0.000
//5.4 would become 5.400
break;
case 4:
temp_char[4] = "\0";
//15.2 would become 15.20
//-7.4 would become -7.40
break;
// -15.3 is in right format already
} | E.g. I tried for 15.4 and get
Serial.println(temp_char[0]); | 1
Serial.println(temp_char[1]); | 5
Serial.println(temp_char[2]); | .
Serial.println(temp_char[3]); | 4
Serial.println(temp_char[4]); | ؟
return temp_char;
}
但是,当我执行应用程序时,我将奇怪的字符作为 ArduinoIDE 中的输出(反转问号、方 block 等)。 可能是什么问题?我该如何解决这个问题?或者你能建议更好的方法吗?现在谢谢..
注意:这个问题(问题)的起源更多是关于嵌入式系统的,我在 Electronics StackExchage 上问了另一个问题作为对这个问题的引用(如果你想要/需要 you can read here)
最佳答案
至少三个问题。首先,temp_char[]
声明的大小为 5,但您试图用“EEEEE”(尾随零)将 6 个字符放入其中,并使用 temp_char[5 ]
(只有值 0..4 是合法的)。
其次,赋值 temp_char = "EEEEE"
只是改变了指针,它实际上并没有将任何内容复制到 temp_char
中。为此,您需要 strcpy()
或类似的东西。
第三,你混淆了类型:
temp_char[4] = "0";
temp_char[4]
是 char
类型。 "0"
是 char *
类型,也就是说,它是一个指向字符的指针,而不是一个字符,所以你只是得到一些随机数的低 8 位内存地址。你可能是说:
temp_char[4] = '0';
因为 '0'
是 int
类型,代表一个 ASCII 值,在分配时将被适本地截断为 8 位。
关于c - 如何在 C 中的 char 数组末尾添加一个 char(零)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561658/