Const char pointers / constant char array / string?

Hello. In an example of one library, I met the following code:

const char* ssid = "My_WiFi_ssid";
const char* password = "My_WiFi_password";

And then running

  WiFi.begin(ssid, password);

Why? for What?
If I understand correctly, then two pointers are created, and addresses are written in them as a string? And then this "address" is read, which is a "string".
Why not create a simple string and access the contents of that variable?

What do you consider a "simple string"?

You are passing these two pointers to WiFi.begin which sets up some conditions necessary.
In WiFi.begin the pointers are used to retrieve the string data.

String ssid = "My_WiFi_ssid";

or

char ssid[32] = "My_WiFi_ssid";

Well this is a waste of about 25 bytes:

char ssid[32] = "My_WiFi_ssid";

You could use

const char ssid[] = "My_WiFi_ssid";
1 Like

Why are we writing the string where the address should be?

Whatever that means...

The pointers (each 2 bytes each) are passed, not the strings.

These pointers say where to find the strings.

Why is it used

const char* ssid = "My_WiFi_ssid";

not this?

const char myssid[] = "My_WiFi_ssid";
const char *ssid = myssid[];

But nobody created the string themselves. Or are they created at the moment of declaring a pointer with a value?

have a read about const pointers and pointers to const values

2 Likes

My personal preference is the following, which creates the char arrays and stores the text in them.

const char ssid[] = "My_WiFi_ssid";
const char password[] = "My_WiFi_password";

The original version, without any compiler optimizations, would store the text in char arrays, then create a separate char* to store the pointer to the char array, using more memory in the process. As a practical matter, the compiler likely never actually stores the pointers.

const char* ssid = "My_WiFi_ssid";
const char* password = "My_WiFi_password";

This will likely not compile, and basically does the same as the original, except that myssid can now be referenced in the code separately from ssid.
< edit > The most common reason for doing it this way, creating the char array and char* separately, is when you want the compiler to store both in the flash memory on a processor that has flash memory in a separate address space from the ram (reference the use of PROGMEM).

const char myssid[] = "My_WiFi_ssid";
const char *ssid = myssid[]; //likely compiler error because of the []
1 Like

Thanks! This is what I didn't understand.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.