c - 这两个 char 数组的值有什么区别?
问题描述
我正在编写 C 中的代码,该代码读取温度并将其发送到使用 GTK3 制作的 GUI。
这是代码:
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
char Vo[10]; // voltage out
float Ro, R1 = 6247; // value of resistance at 20C in the thermistor
float T0 = 298.15; // 25 degrees C in Kelvin
float logR2, R2, T;
float A = 1.281426510e-03, B = 2.368116050e-04, C = 0.9002008458e-07; // Steinhart-Hart and Hart Coefficients
char *senseTemp() {
FILE *fp;
char command[50];
int c;
//get the Analog value
fp = fopen("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r");
if (fp == NULL) {
perror("Error: ");
return (1);
}
int i = 0;
while (1) {
c = fgetc(fp);
if (feof(fp)) {
break;
}
printf("%c ", c);
if (c != EOF) {
Vo[i] = c;
++i;
}
}
fclose(fp);
//printf("Analog Reading: %s\n", Vo);
//convert the value to resistance
int V = 0;
float Vout = 0;
V = atoi(Vo); //TO convert an array to an integer
//printf("Value of V: %d\n", V);
Vout = V * (1.8 / 4095.0); //Voltage out of the thermistor
//printf("Voltage out from thermistor: %f\n", Vout);
R2 = R1 * ((1.8 / Vout) - 1);
logR2 = log(R2);
T = (1.0 / (A + B * logR2 + C * logR2 * logR2 * logR2)); // Steinhart and Hart Equation. T = 1 / {A + B[ln(R)] + C[ln(R)]^3}
T = T - 273.15;
char Tfinal[10];
i = 0;
snprintf(Tfinal, 10, "%.0f", T);
printf("Here is the value: %s\n", Tfinal);
return Tfinal;
}
如果我使用return Vo;
这些值正确返回到 GUI 并且我可以看到它们,但我想将这些值转换为摄氏度,这就是变量 T 所持有的。但是gtk_label_set_text()
在 GUI 中显示温度的只需要一个指向字符串的指针。
所以在我的代码中,如果我使用return Vo
它可以工作但不能与return Tfinal
.
解决方案
return Tfinal;
具有未定义的行为,因为您返回具有本地自动存储的数组的地址。该数组在函数返回时被丢弃。分配数组以malloc()
将其返回给调用者。
推荐阅读
- python - 如何根据另一个数据框选择一个数据框的值
- c - make 源中的 floc 和 RETSIGTYPE
- unix - 如何使用unix在某个列中添加单引号
- c++ - 为什么这段代码会导致分段错误?
- android - 通过通知让我的颤振应用程序在后台运行
- python - SelectKBest fit:ValueError:无法将字符串转换为浮点数
- docker - 挂在“设置 docker-ce (5:19.03.8~3-0~ubuntu-bionic) ...”
- javascript - 在 Next.js API Route 中进行外部 API 调用时遇到错误
- javascript - JS:仅从数组中提取唯一属性对象
- java - 如何为聚合查询创建 Spring Boot 存储库查询?