#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
char var[MAX] = {'a', 'b', 'c'};
char *ptr;
// 指针中的数组地址
ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << (int *)ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// 移动到下一个位置
ptr++;
}
return 0;
}
输出结果:
Address of var[0] = 0x7fffd63b79f9
Value of var[0] = a
Address of var[1] = 0x7fffd63b79fa
Value of var[1] = b
Address of var[2] = 0x7fffd63b79fb
Value of var[2] = c
int swap(int& a, int& b)
{
int temp;
temp = a ^ b;
a = temp ^ a;
b = temp ^ b;
return 0;
}
这里利用了数异或的性质,一个数与其本身异或等于 0,0 与一个数异或不改变该数。
1966cpp-function-call-by-value
使用异或运算交换两数的值:
#include <iostream>
using namespace std;
void swap(int a, int b)
{
a=a^b;
b=a^b;
a=a^b;
return;
}
int main ()
{
// 局部变量声明
int a = 100;
int b = 200;
cout << "交换前,a 的值:" << a << endl;
cout << "交换前,b 的值:" << b << endl;
// 调用函数来交换值
swap(a, b);
cout << "交换后,a 的值:" << a << endl;
cout << "交换后,b 的值:" << b << endl;
return 0;
}
#include <iostream>
using namespace std;
void swap(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
return;
}
int main ()
{
// 局部变量声明
int a = 100;
int b = 200;
cout << "交换前,a 的值:" << a << endl;
cout << "交换前,b 的值:" << b << endl;
// 调用函数来交换值
swap(a, b);
cout << "交换后,a 的值:" << a << endl;
cout << "交换后,b 的值:" << b << endl;
return 0;
}
1969cpp-pointer-to-an-array
C++ 中,将 char * 或 char[] 传递给 cout 进行输出,结果会是整个字符串,如果想要获得字符串的地址(第一个字符的内存地址),可使用以下方法:
强制转化为其他指针(非 char*)。可以是 void *,int *,float *, double * 等。* 使用 &s[0] 不能输出 s[0](首字符)的地址。因为 &s[0] 将返回 char*,对于 char*(char 指针),cout 会将其作为字符串来处理,向下查找字符并输出直到字符结束 *。
输出结果:
1968cpp-multi-dimensional-arrays
如果想从键盘中获取值,来构建二维数组,可以使用如下写法构建:
1967cpp-function-call-by-reference
这里利用了数异或的性质,一个数与其本身异或等于 0,0 与一个数异或不改变该数。说到 swap,我想起了优化的 swap,可能稍微难理解一点。
这里利用了数异或的性质,一个数与其本身异或等于 0,0 与一个数异或不改变该数。
1966cpp-function-call-by-value
使用异或运算交换两数的值:
更多内容参考:C 关于使用异或运算交换两数的值
1965cpp-function-call-by-value
不用临时变量: