Can I increment a char* passed to a function?

c++, function, pointers, reference

Solution

Since you are not passing your arguments by reference, the compiler creates a copy of the pointer and modifies the copy accordingly within the function.

Change your function signature to the following.

void writeOut(char*& output, string data, const int length)

You may also want to consider passing `string` as `const string&` if you don't plan to modify it.

Problem

I'm working on a C++ application that will build a fixed-length record from a set of database fields. I'm writing a function that will accept the output record as a `char*`, the string to write, and the total length of the field. The purpose of the function is to copy the string to the current position of the char pointer, and then fill the rest of the length with spaces. Here's a simplified example of what I'm doing. ``` void writeOut(char* output, string data, const int length) { if ((int) data.size() > length) { //Just truncate it data = data.substr(0, length); } int index = 0; while (index < (int) data.size()) { *output++ = data[index++]; } while (index++ < length) { *output++ = ' '; } } int test() { char output[100]; writeOut(output, "test1", 10); writeOut(output, "test2", 10); writeOut(output, "test3test4test5", 10); cout << output; } ``` I expected to see something like this. ``` test1 test2 test3test4 ``` Instead all I get is... ``` test3test4 ``` So it's incrementing the `char*` within the function, but only within the function. When the function ends the `char*` is right back where it started. Is it possible to pass a pointer in such a way that the pointer is updated in the calling function? In case you can't tell, I'm pretty new to C++. Any suggestions will be appreciated.

Original source