首页 > 解决方案 > 这两个 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.

标签: cfloating-pointgtkgtk3

解决方案


return Tfinal;具有未定义的行为,因为您返回具有本地自动存储的数组的地址。该数组在函数返回时被丢弃。分配数组以malloc()将其返回给调用者。


推荐阅读