1

I have the following very simple program.

int modify(char * v){
  v = "123" ;

  return 0;
}

int main (int argc, char** argv){
char *test = new char[10];
  modify(test);
  std::cout << test;
  return 0;

}

I know I can just print out "123", but I deliberately wrote it that way to learn about how pointers work. However, "123" is not printed. How should I correctly pass the pointer?

Mariska
  • 1,913
  • 5
  • 26
  • 43

3 Answers3

7

You have to remember that in C++ arguments are by default passed by value, meaning that in the function you have copies., and modifying a copy will not change the original.

If you want to change the pointer to point to something else you need to pass it by reference. However, in this case it will cause other problems, as you then loose the original pointer.

So the solution is to either use std::string passed by reference, or by using strcpy top copy into the destination memory area (but if you use strcpy you have to take care to not write beyond the allocated memory).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

Try this inside modify strcpy(v, "123")

Prabhu
  • 3,434
  • 8
  • 40
  • 48
1

There are several problems with your code.

Your modify() function actually changes nothing:

int modify(char * v) {
  v = "123"; // overwrites the parameter value copy on the stack
             // with a char[] literal pointer
  return 0;
}

You need to copy from the literal to the pointer:

int modify(char* v) {
  strcpy(v,"123");
  return 0;
}

You do not free the allocated memory, which may lead to memory leaks in other situations

int main (int argc, char** argv){
char *test = new char[10];
  modify(test);
  std::cout << test;
  delete [] char; // <<< Note
  return 0;    
}

As Joachim Pileborg already mentioned the most approriate solution for c++ would be to use a std::string instead of char*.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190