通过引用传递字符串变量
我有这段代码:
#include <stdio.h>
#include <string.h>
void b(char *in, char ** out);
int main()
{
char a[] = {'w','o','r','l','d',' '};
char *d = nullptr;
b(a, &d);
printf("hello %sn", d);
return 0;
}
void b(char *in, char ** out)
{
char tmp[10];
for(int i=0;i<6;i++)
tmp[i]=in[i];
*out=tmp;
printf("%sn", *out);
}
我除了得到论文 printf :
world
hello world
但我得到这些:
world
hello
为什么 d 变量未满?:(
感谢您提供有关此的任何线索!
回答
在 内部b(),您将char*引用的 by设置out为指向本地char[]数组,该数组不是以 null 结尾的(因此"%s"进入printf()),但在b()退出时也会超出范围,因此调用者(即main())以悬空结束char*指向无效内存的指针。
您将问题标记为c++。C++ 不是 C。你应该在这种情况下使用std::string而不是char[],例如:
#include <iostream>
#include <string>
void b(const std::string &in, std::string &out);
int main()
{
std::string a = "world";
std::string d;
b(a, d);
std::cout << "hello " << d << "n";
return 0;
}
void b(const std::string &in, std::string &out)
{
std::string tmp = in.substr(0, 6);
out = tmp;
std::cout << out << "n";
}
否则,如果你真的想char*在 C 或 C++ 中使用 , 你将需要使用动态内存分配,例如:
#include <stdio.h> // or <cstdio> in C++
#include <string.h> // or <cstring> in C++
void b(char *in, char ** out);
int main()
{
char a[] = "world";
char *d = nullptr;
b(a, &d);
printf("hello %sn", d);
delete[] d; // or free() in C
return 0;
}
void b(char *in, char ** out)
{
char *tmp = new char[7]; // or malloc() in C
for(int i = 0; i < 6; ++i) {
tmp[i] = in[i];
}
tmp[6] = ' ';
*out = tmp;
printf("%sn", *out);
}