Copy uint8_t[] to another uint8_t[]

bibble235
Posts: 13
Joined: Mon May 28, 2018 11:23 pm

Copy uint8_t[] to another uint8_t[]

Postby bibble235 » Fri Jul 27, 2018 12:38 am

Hi,

I want to pass the username and password into the function to initialize the wi-fi.

Code: Select all

void initialize_wifi_sta(uint8_t inSSID[], uint8_t inPassword[])
{
	uint8_t fred1[32];
	uint8_t fred2[32];
	std::copy(std::begin(fred1), std::end(fred1), std::begin(fred2));
	
	wifi_config_t myWifiConfiguration;
	std::copy(std::begin(*inSSID), std::end(*inSSID), std::begin(myWifiConfiguration.sta.ssid));
}
The first example fred1 -> fred2 works but I cannot seem to get this to work for a real example.

Thanks,

ESP_Sprite
Posts: 9708
Joined: Thu Nov 26, 2015 4:08 am

Re: Copy uint8_t[] to another uint8_t[]

Postby ESP_Sprite » Fri Jul 27, 2018 1:07 am

1. You're dereferencing inSSID, (*inSSID) where you don't do that anywhere else,
2. The compiler knows the size of fred1/fred2 (because you're declaring them as an array of 32 elements) but not of inSSID, which you're more-or-less defining as a pointer.

Seeing inSSID most likely is zero-terminated, you can do
strcpy(myWifiConfiguration.sta.ssid, inSSID);
but seeing as this may write past the end of the ssid field, it's better to do
strncpy(myWifiConfiguration.sta.ssid, inSSID, sizeof(myWifiConfiguration.sta.ssid));

bibble235
Posts: 13
Joined: Mon May 28, 2018 11:23 pm

Re: Copy uint8_t[] to another uint8_t[]

Postby bibble235 » Fri Jul 27, 2018 4:49 am

I don't think you can use strcpy to strncpy with a uint8_t.

I know I can use

Code: Select all

	wifi_config_t myWifiConfiguration;
	memcpy(myWifiConfiguration.sta.ssid,inSSID.c_str(),inSSID.length());
	myWifiConfiguration.sta.ssid[inSSID.length()] = '\0';
	memcpy(myWifiConfiguration.sta.password,inPassword.c_str(),inPassword.length());
	myWifiConfiguration.sta.password[inPassword.length()] = '\0';
But it does look a bit rubbish

ESP_Sprite
Posts: 9708
Joined: Thu Nov 26, 2015 4:08 am

Re: Copy uint8_t[] to another uint8_t[]

Postby ESP_Sprite » Fri Jul 27, 2018 8:15 am

Actually you can; str[n]cpy doesn't really care about the data content, just that it's zero-terminated. The compiler may balk at you, however, and you can get around that by casting:
strncpy((char*)myWifiConfiguration.sta.ssid, (char*)inSSID, sizeof(myWifiConfiguration.sta.ssid));

Who is online

Users browsing this forum: Bing [Bot], Majestic-12 [Bot] and 86 guests