在c/c++中使用malloc在另一个函数中填充char*



我正在为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] = '';
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是函数的局部变量

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,您需要取消引用由表达式&password初始化的参数buff

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

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

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

最新更新