gpt4 book ai didi

c++ - 在 C++ 中初始化指针是强制性的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:11 26 4
gpt4 key购买 nike

在给t赋值之前,是否必须在下面的代码中初始化t?代码是否正确?

void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}

最佳答案

你不需要指针开始:

void swap(int *x,int *y)
{
int t; //not a pointer!
t=*x;
*x=*y;
*y=t;
}
int a = 10, b = 20;
swap( &a, &b); //<-----------note : Needed &

--

或者,您可能需要以下交换功能:

void swap(int & x,int & y) //parameters are references now!
{
int t; //not a pointer!
t=x;
x=y;
y=t;
}
int a = 10, b = 20;
swap(a,b); //<----------- Note: Not needed & anymore!

关于c++ - 在 C++ 中初始化指针是强制性的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5403882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com