I'm having some problems with pointers. Help would be much appreciated.
I'm trying to change the value of a character array inside a function. My code is split into three files. It compiles but doesn't do what it is supposed to do. I'm kind of new to pointers but I'm pretty sure that they are causing the problem.
Here is my code:
extras.h:
1 2 3 4 5
# include <iostream>
# include <sstream>
# include <string>
void nameWithPaddedNumber(char _name[], int number, int digits, char* destination);
You're assigning dest to the local variable destination, so that change will never leave the function.
You need a pointer to a pointer (char**) or far better yet, a reference or pointer to a real string (string&).
I can immediately see that padd was never initialized. Therefore the first time you send padd to cout the system will start printing whatever characters happen to be in memory until a 0 is found. Therefore I would expect to see a bunch of garbage being printed. What exactly are you having trouble with? What did you expect to happen?
kempofighter, I want padd to start off as garbage but then change inside the function. So I pass in a reference to padd. But after the function is called padd remains garbage instead of being changed to daria_walk_0014.
Athar, you may be right but I don't know what is supposed to be a pointer to a pointer or reference to a string.
dest = newchar[padded.length()+1];
dest[padded.length()]=0;
memcpy(dest,padded.c_str(),padded.length());
destination = dest;
Here is your other problem. You don't need to allocate memory for this new thing "dest". You should be copying directly into destination and you'd be fine. The problem is that destination was a copy of padd which started out with the same address as padd. Then you overwrite it with a pointer to the new memory. After returning from the function padd in main has its original value and still points to the same garbage. You don't need to do char**. You just need to write to the memory pointed to by destination in the first place. You've also created a memory leak by dynamically allocating memory without ever deleting it.
Also if you are going to use the char array use strcpy not memcpy. strcpy will copy the NULL for you and is specifically designed to deal with character arrays that are NULL terminated. Alternatively use std::string and pass the object by reference or by iterators to the start and end.