尝试以下操作:
void function(char* MyArray)
{
MyArray = "Hello World";
std::cout << "Address of MyArray inside function: " << (void*)MyArray << std::endl;
}
int main()
{
char MyArray[10];
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
function(MyArray);
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
std::cin.get();
return 0;
}
有了这个,你会看到指向你的数组的指针只是函数内部的一个副本。通过分配“Hello World”,您只更改副本的地址,而不是主函数中数组的地址。
这个例子实际上可以工作,因为这样你在函数中没有指针的副本:
void function(char** MyArray)
{
*MyArray = "Hello World";
std::cout << "Address of MyArray inside function: " << (void*)*MyArray << std::endl;
}
int main()
{
char* MyArray = 0;
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
function(&MyArray);
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
std::cin.get();
return 0;
}
但这仍然是不好的风格。使用字符数组时,您应该执行以下操作:
void function(char* MyArray)
{
strcpy(MyArray, "Hello World");
std::cout << "Address of MyArray inside function: " << (void*)MyArray << std::endl;
}
int main()
{
char* MyArray = 0;
MyArray = new char[15];
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
function(MyArray);
std::cout << "Address of MyArray outside function: " << (void*)MyArray << std::endl;
delete [] MyArray;
std::cin.get();
return 0;
}
但正如其他人提到的,我会使用 std::string 并通过引用传递它,而不是使用字符数组。因为与 std::string 相比,字符数组是不安全的。像这样:
void function(std::string& MyString)
{
MyString = "Hello World";
}
int main()
{
std::string MyString;
function(MyString);
std::cin.get();
return 0;
}