【问题标题】:Fill a char* in another function using malloc in c/c++在 c/c++ 中使用 malloc 在另一个函数中填充 char*
【发布时间】:2021-09-20 09:26:31
【问题描述】:

我正在为 Arduino (ESP8266) 编写代码,并且必须从文件中读取一个字符串才能使用它。我不知道那个文件有多长,所以我必须创建一个char* 并将其传递给readConf 函数,以便malloc 决定内存大小。

void readConf(char path[], char **buff){
    SPIFFS.begin();
    if (SPIFFS.exists(path))
    {
        File file = SPIFFS.open(path, "r");
        int size = file.size();
        Serial.print("File size: ");
        Serial.println(size);
        char *bu;
        bu = (char*) malloc((size+1) * sizeof(char));
        file.read((uint8_t*) bu, size);
        bu[size] = '\0';
        Serial.print("Data: ");
        for (int i = 0; i < size; i++)
            Serial.print(bu[i]);
        Serial.println("");
        //Everything is OK. It is printed correctly.
        buff = &bu; //!This is the problem!
        file.close();
    }
    SPIFFS.end();
}

#define file_path "/file"
void setup(){
    
    if(WiFi.getMode() != WIFI_STA)
        WiFi.mode(WIFI_STA);
    
    char* username;
    readConf(file_path, &username);
    char* password;
    readConf(file_path, &password);
    /*The same with password. */
    WiFi.begin(username, password);
    
    Serial.print("username: ");
    Serial.println(username); //Here I sometimes get Exception, and sometimes prints non-sense characters
    free(username); //My memory is limited. I'm doing all this stuff for this line!
    //...
}

我也在StackOverflow和其他网站上搜索了很多,也使用了char *char **,直接在readConf函数中填充指针,还有很多但没有一个起作用。我应该如何处理?我能做到吗?

注意:我不应该使用 String 类。

【问题讨论】:

  • 改用*buff = bu。或者,如果您真的在使用 C++ 编程,请使用 实际 引用而不是指针来模拟引用。
  • @Someprogrammerdude 我以前遇到很多硬件异常,结果Arduino会一次又一次地重启。我必须这样使用它。
  • 顺便问一下,为什么你现在使用 Arduino 标准 String 类作为你的字符串?
  • @Someprogrammerdude 硬件异常:)) 我有同样的错误:stackoverflow.com/questions/60966280/…,所以stackoverflow.com/a/60969009/9691976 说:This error pattern is typical for the String class.

标签: c++ c malloc esp8266


【解决方案1】:

函数参数buff是函数的局部变量

void readConf(char path[], char **buff){

所以在函数中改变它

buff = &bu; //!This is the problem!

对函数setup中声明的变量password没有影响

char* password;
readConf(file_path, &password);

你需要写

*buff = bu;

即你需要在函数readConf中改变函数setup中声明的指针password的值

所以你通过指向它的指针通过引用将指针传递给函数readConf

readConf(file_path, &password);

现在要直接访问原始指针 password,您需要取消引用由表达式 &amp;password 初始化的参数 buff

【讨论】:

  • 您能解释一下吗?为什么我的错了,你写的第二个没问题?
  • @MohammadKholghi 请参阅我的附加答案。
【解决方案2】:

此函数将返回文件大小(以字节为单位)。

#include <fstream>

std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg(); 
}

字符* buff; - 那是指向 char 数组的指针。不是 char** buff;

【讨论】:

  • 这不是关于计算机文件系统的问题
  • 非常感谢,但真正的问题不在于文件大小。这是关于指针的。
  • 我想我也澄清了指向 shar 数组的指针。
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 2021-09-19
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 2012-01-23
相关资源
最近更新 更多