0
int main(int args, char* argv[]) {
    string* list;
    listDevices(list);
    printf("device 0: %s\n", list[0]); // prints some junks
}

void listDevices(string* list) {
    list = new string[1];
    list[0] = "abc";
    printf("device 0: %s\n", list[0]); //prints "abc"
}

In the above code, list array is initialized and assigned some values in the listDevices method, but when I print it outside the function, some junks would be printed.

Why does it work correctly if I send string list[1] as input to the above method but not when sending string* list (although both are pointers)?

Jongware
  • 22,200
  • 8
  • 54
  • 100
user3406222
  • 309
  • 2
  • 11

3 Answers3

3

You only change a local copy of the pointer in listDevices. The pointer in main remains unchanged. You probably want to return a pointer to the new list:

string *listDevices() {
    string *list = new string[1];
    list[0] = "abc";
    printf("device 0: %s\n", list[0]); //prints "abc"
    return list;
}

int main(int args, char* argv[]) {
    string *list = listDevices();
    printf("device 0: %s\n", list[0]); // Will now work
}

Alternatively, you can pass the pointer by reference, but I prefer the return method for stylistic reasons.


By the way, you probably do not need to use a pointer and printf in the first place. Most likely, your code should look somewhat like this:

std::string listDevices () {
    std::string ret = "abc";
    std::cout << ret << "\n";
    return ret;
}

int main () {
    std::string str = listDevices();
    std::cout << ret << "\n";
}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
2

list is a variable of type pointer-to-string, which you pass by value. Changing list itself inside the method won't carry the changes outside the scope of the method.

You want to pass it by reference:

void listDevices(string*& list)
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

You need to pass list as reference to function as:

void listDevices(string* &list) {
    list = new string[3];
    list[0] = "abc";
    printf("device 0: %s\n", list[0].c_str()); //prints "abc"
}

int main(int args, char* argv[]) {
    string* list=nullptr;
    listDevices(list);
    printf("device 0: %s\n", list[0].c_str()); //now prints "abc"
    // Don't forget to do `delete[] list` at the end !
    return 0;
}

Note: As you tag c++ in your question, check this link which indicate to using .c_str() while printing a std::string with printf.

caution: Don't forget to do delete[] list at the end !

Community
  • 1
  • 1
Emadpres
  • 3,466
  • 2
  • 29
  • 44