1. 当要用到很大的数的时候用 long long n;来定义,其输出形式为:printf("%I64d",n);注意这里是大写的 i ,也可以用%IId输出。
2.在函数参数中的*、&、*&,
在链表中,void InitLink(LinkList *&head)初始化链表的时候,这里的*&是把指针的地址传进来了,在main函数中定义头节点:LinkList *head; 使用函数的时候为:InitLink(head); 就可以了
在代码
#include <iostream>
using namespace std;
void test(int *&p,int &a)
{
cout<<&p<<endl; //3
cout<<&a<<endl; //4
}
int main()
{
int a = 0;
int *p = &a;
cout<<&p<<endl; //1
cout<<&a<<endl; //2
test(p,a);
return 0;
}
中,1和3的输出结果是一样的,2和4的输出结果是一样的。
在代码:
#include <iostream>
using namespace std;
void test(int *p,int &a,int &b)
{
cout<<p<<endl;
cout<<&a<<endl;
p=&b;
cout<<*p<<" "<<p<<endl;
}
int main()
{
int a = 0,b=2;
int *p = &a;
cout<<&a<<endl;
cout<<&b<<endl;
test(p,a,b);
cout<<*p<<" "<<p<<endl;
return 0;
}
//运行结果(每个电脑上运行结果中的地址不一定一样):
// 0x6ffe44
// 0x6ffe40
// 0x6ffe44
// 0x6ffe44
// 2 0x6ffe40
// 0 0x6ffe44
从这个大代码中可以看到,如果传参数的地址,才会改变那个参数的值。普通变量的地址是为:*t,传指针的地址为*&t。在传入函数中的用法和main函数中的一样。 当函数为void f(int *p);在主函数中定义int *p; f(p),这时在f函数中,如果有对指针p指向的整数作改变时,在函数结束后仍有效。若对指针p改变是,即让他指向另一个地址,则在函数结束后p指向原来的地址,不改变。下面代码:
#include<stdio.h>
void f(int *p)
{
(*p)++;
}
int main()
{
int a=1;
int *p=&a;
f(&a);
printf("%d",*p);
} //输出的结果为2
函数参数为指针,调用函数的时候传a的地址,这个时候有效,就相当与把a的地址传给指针p。
代码:
#include<stdio.h>
void f(int &a)
{
a++;
}
int main()
{
int a=1;
int *p=&a;
f(a);
printf("%d ",a);
f(*p);
printf("%d ",a);
}
//运行的结果为 2 3因为这个时候函数的参数是整数类型的地址,调用的时候传整数就行,因为a和*p等价,所以效果一样
3. 在链表和栈等数据结构中,先定义结构体,在main函数中声明一个指针之后,要开辟一个区域,是指针指向这个区域,可以在main函数中开辟这个区域,也可以在初始化函数中开辟这个区域。指针定义了之后就要让他指向一个地址。
4.声明一个指针时候,他的默认值不是NULL,而是随机指向一个地址。
(1)string和字符数组转化为int、float,头文件为#include<stdlib.h>代码如下:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
string s1="124";
char s2[10]={'1','2','3'};
int a;
float f;
a=atoi(s1.c_str()); cout<<a<<" ";
f=atof(s1.c_str()); cout<<f<<endl;
a=atoi(s2); cout<<a<<" ";
f=atof(s2); cout<<f<<endl;
}
#include<iostream>
#include<sstream>
using namespace std;
string inttranstr(int t)
{
stringstream ss;
ss<<t;
return ss.str();
}
string floattranstr(float t)
{
stringstream ss;
ss<<t;
return ss.str();
}
int main()
{
int a=123;
float f=456.789;
string s1;
s1=inttranstr(a); cout<<s1<<" ";
s1+=floattranstr(f); cout<<s1<<" ";
}
#include<iostream>
using namespace std;
int main()
{
char *n[10]={"213","432"};
cout<<n[0]<<endl<<n[1]<<endl;
}
8.swap函数,int a=1,b=2; swap(a,b);