简体   繁体   中英

Initializing char pointer

I have a function

ValArgument(char* ptr){
   char str[] = "hello world";
   ptr = &str[0];
}

In this function, I want to init a char array and add it to the char pointer ptr. I call the function like that:

char* ptr= NULL;
ValArgument(ptr);

The pointer returned still has the value NULL. Why? I expected that the pointer will point onto the char array str[].

The pointer returned still has the value NULL. Why?

Because you passed the pointer by value. That means that the function is given a separate copy of the pointer, and any changes it makes to the pointer will not affect the caller's copy.

You can either pass by reference:

void ValArgument(char *& ptr)
//                     ^

or return a value:

char * ValArgument();

I expected that the pointer will point onto the char array str[].

No; once you've fixed that problem, it will point to the undead husk of the local variable that was destroyed when the function returned. Any attempt to use the pointer will cause undefined behaviour.

Depending on what you need to do with the string, you might want:

  • a pointer to a string literal, char const * str = "hello world"; . Note that this should be const , since string literals can't be modified.
  • a pointer to a static array, static char str[] = "hello world"; . This means that there is only one string shared by everyone, so any modification will affect everyone.
  • a pointer to a dynamically allocated array. Don't go there.
  • a string object, std::string str = "hello world"; . This is the least error-prone, since it can be passed around like a simple value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM