Home > OS >  Change global string pointer variable from inside a function?
Change global string pointer variable from inside a function?

Time:10-20

Firstly i would like to apologize beforehand about this question. I imagine that it must be really straight forward, but i'm a beginner and had nowere to go.

I'm declaring the following pointers, outside all my functions (Global Variable):

#include <ESP8266WiFi.h>

String* IP;
String* MAC;

Then, from inside a function i'm trying to change it's values:

void networkInfo() {
    String* IP = WiFi.localIP().toString();
    String* MAC = WiFi.macAddress();
}

When i try to compile and execute, it gives me the following error:

error: cannot convert 'String' to 'String*' in initialization
String* IP = WiFi.localIP().toString();
                                                           ^

error: cannot convert 'String' to 'String*' in initialization
String* MAC = WiFi.macAddress();

                                                     ^

Please, what am i doing wrong? Thanks...

PS: I would like to state that before asking this question i REALLY did search on StackOverflow, tried many different approachs but none helped for me. (Most were incomplete or just really specific to the OPs question)

If this is a duplicate, i'm sorry. I didnt find the solution for this.

CodePudding user response:

First, you are declaring local variables that are hiding the global ones.

String* IP = (value)

Should just be

IP = (value)

Second, a pointer must be assigned the address of (something) not the (something) itself.

IP = new String

Will allocate a persistent string object on the heap and set IP to the address of it (a pointer to it).

Now that IP points to a String, *IP is the string and this will work

*IP = WiFi.localIP().toString();

As @CherryDT notes, you probably only want to allocate storage for the global variables once, in some initialization function. If you keep allocating new objects every time this function is called you will leak memory.

CodePudding user response:

You're trying to put a String value into a String pointer type.

String* IP = WiFi.localIP().toString();
    //  ^ This variable is          ^This returns a String.
    //    a String* (string
    //    pointer) type

You're also redeclaring the variables IP and MAC in your networkInfo() function.

I don't know why you have IP and MAC as String pointers, you shouldn't need to. But, if you insist on keeping them that way you just need to do:

*IP = WiFi.localIP().toString();
  • Related