-1

The following code works:

#include <ESP8266WiFi.h>

const char *ssid =  "Your wifi Network name";     // replace with your wifi ssid and wpa2 key
const char *pass =  "Network password";

WiFiClient client;

void setup() 
{
   Serial.begin(9600);
   delay(10);

   Serial.println("Connecting to ");
   Serial.println(ssid); 

   WiFi.begin(ssid, pass); 
   while (WiFi.status() != WL_CONNECTED) 
   {
      delay(500);
      Serial.print(".");
   }
   Serial.println("");
   Serial.println("WiFi connected"); 
}

But when the line:

const char *pass = "Network password";

is replaced with:

const char pass = "Network password";

The compiler throws an error.

Why does the character pointer (I think it is a pointer) make the code work, when it is never used elsewhere throughout the code?

I have had a look at the following link, but I am getting confused about the explanation:

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]

at0S
  • 4,522
  • 2
  • 14
  • 10
Angus
  • 78
  • 8
  • Were you trying to do this "char ssid = "Your wifi Network name"; '? – David Ledger Sep 25 '19 at 00:13
  • I was wondering why I needed the *char and why char wouldn't work – Angus Sep 25 '19 at 00:16
  • 1
    `char` is a single character. It can't hold `"Network password"`. You need an array to copy the literal into or to just point at the literal they way you are doing in the working code. – user4581301 Sep 25 '19 at 00:18
  • 2
    char is just the representation of one character. const char * is a pointer to a single character. A string literal in C++ and C is a block of characters in memory that occur one after the other (contigious is the word for that). Adding the pointer points to that block of characters in memory. A string in C also always ends in a null character, so when you have a pointer to the start of the string a program knows the string continues until a null character (a zero) is encountered. – David Ledger Sep 25 '19 at 00:19
  • 1
    Ah, this makes sense, thanks. I think I will do some more research into this though – Angus Sep 25 '19 at 01:11

1 Answers1

3

A char is a single character. A char* is a pointer to a char.

A string literal is a fixed-length const char[] array of characters. You can assign a const char[] array to a const char* pointer, as the reference to the array name will decay into a pointer to the 1st element in the array. That is why const char *ssid = "Your wifi Network name"; works.

You can't assign a const char[] array or a const char* pointer to a single char. That is why const char pass = "Network password"; does not work.

And yes, the pointers are being used in the code, despite your claim that they are not. The ssid pointer is being passed as input to Serial.println() , and the ssid and pass pointers are both being passed as input to WiFi.begin(). Both of those functions take strings as their input.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770