Joh*_*ant 3 c++ pointers reference function
我正在研究一个C++应用程序,它将从一组数据库字段构建一个固定长度的记录.我正在编写一个函数,它将接受输出记录作为a char*
,要写入的字符串以及字段的总长度.该函数的目的是将字符串复制到char指针的当前位置,然后用空格填充剩余的长度.这是我正在做的简化示例.
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望看到这样的事情.
test1 test2 test3test4
Run Code Online (Sandbox Code Playgroud)
相反,我得到的只是......
test3test4
Run Code Online (Sandbox Code Playgroud)
所以它char*
在函数内递增,但仅在函数内.当功能结束时,char*
它正好在它开始的地方.是否可以以在调用函数中更新指针的方式传递指针?
如果你不能说,我对C++很新.任何建议将不胜感激.
您想要将char**传递给该函数.
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];
char *pos = output;
writeOut(&pos, "test1", 10);
writeOut(&pos, "test2", 10);
writeOut(&pos, "test3test4test5", 10);
cout << output;
}
Run Code Online (Sandbox Code Playgroud)
(手头没有编译器,但这应该工作)
由于您没有通过引用传递参数,因此编译器会创建指针的副本并在函数内相应地修改副本.
将您的功能签名更改为以下内容.
void writeOut(char*& output, string data, const int length)
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑传递string
,就const string&
好像您不打算修改它一样.
你可以通过保留一个新的字符指针来完成你所追求的目标,但你不能增加"输出"变量,然后再次使用它 (不在你的cout行中).
例如,您可以执行以下操作:
char* 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++ = ' ';
}
return output; // return the new position here!
}
int test() {
char output[100];
char *outputLocation = output;
outputLocation = writeOut(outputLocation, "test1", 10);
outputLocation = writeOut(outputLocation, "test2", 10);
outputLocation = writeOut(outputLocation, "test3test4test5", 10);
cout << output;
}
Run Code Online (Sandbox Code Playgroud)