指针无法传递问题

指针无法传递问题

char *Spiffs::wifi_read_account(void)
{
  File file;

  file = SPIFFS.open("/account.txt", FILE_READ);
  if (file)
  {
    char account2[]="1234";
    char account[]="";
    int index=0;
    
    while (file.available())
    {
       account[index]=(char)file.read();
       index++;
      //  Serial.print((char)file.read());
    }
    file.close();
    // Serial.print(account);
    return account2;
  }
}

char *Spiffs::wifi_read_password(void)
{
  File file;

  file = SPIFFS.open("/password.txt", FILE_READ);
  if (file)
  {
    char password[]="";
    int index=0;
    
    while (file.available())
    {
       password[index]=(char)file.read();
       index++;
      //  Serial.print((char)file.read());
    }
    file.close();
    // Serial.print(password);
    return password;
  }
}


  // Serial.print(spiffs.wifi_read_account());
  // Serial.print(spiffs.wifi_read_password());

  // account=spiffs.wifi_read_account();
  // Serial.println(account);
  // password=spiffs.wifi_read_password();
  // Serial.println(password);

指针传递,数组会被释放内存,而指针不会。

  • 函数中不能返回局部变量,因为在c中这些局部变量都是存储在栈中的,随着他们的作用域的消失而消失,局部变量的指针也是局部变量。
  • 如果我们要返回一个局部变量的指针,有两种方法,
  • 一、把这个指针声明为static。(更正,只要被声明为static就都会在整个程序中一直存在。)
  • 二、自己为这个指针所指的内容申请空间,这样的话只要自己没有释放这个变量,这个变量在整个程序的运行过程中就会一直存在。
#include <stdio.h>
#include <iostream>
using namespace std;

void wifi_read(char** password)
{
	static char str[] = "1234";		//局部变量的指针也是局部变量
	*password = (char*)str;

 	//char* str = (char*)"1234";	
	//*password = (char *)str;
	cout << *password;
	cout << "\r\n";
}
int main()
{
	
	char* password = NULL;
	wifi_read(&password);
	cout << password;
	return 0;
}

定义对象时,内存分配问题。

	char str = 'A';
	string password1=NULL; 	//不分配内存,不占内存. 为空引用,即无法对其赋值
	string password2 = ""; 	//分配内存,一个空字符串. 
	string password3;		//分配内存,一个空字符串. 
//也就是null没有分配空间,""分配了空间,因此password1还不是一个实例化的对象,而password2已经实例化

	for (int i = 0; i < 5; i++)
	{
		password2 += str;
	}
	cout << password2;

指针的引用

void wifi_read(char *& password)
{
	password = (char*)"123";
}
int main()
{	
    char *password;
	wifi_read(password);
    cout << password;
}

正确的使用

void wifi_read(char*& password)
{
	static char password_temp[20];//最长20个字符长度
	char source = 'A';

	int index = 0;
	for (int i = 0; i < 20; i++)
	{
		password_temp[index] += source;
		index++;
	}
	password = password_temp;
}
int main()
{
	char* password;
	wifi_read(password);
	cout << password;
}

优化,减少代码量

void wifi_read(char *& password)
{
	char source = 'A';
	static string password_temp;

	for (int i = 0; i < 30; i++)
	{
		password_temp += source;
	}
	password = (char*)password_temp.data();//如果类中没有.data的对象,那就使用.c_str
}
int main()
{
	char *password;
	wifi_read(password);
	cout << password;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值