#include <iostream>
using namespace std;
void equal(char str7[], char str8[])
{
printf("%d\n", str7 == str8);
}
int main() {
char str1[6] = "hello";
char str2[6] = "hello";
char str3[] = "hello";
char str4[] = "hello";
char *str5 = "hello";
char *str6 = "hello";
printf("%d\n", str1 == str2);
printf("%d\n", str3 == str4 );
printf("%d\n", str5 == str6);
equal(str5, str6);
equal(str1, str2);
return 0;
}
注意
int a[] = {1, 2, 3, 4, 5, 6};
//int *p = &a; //错误 等号两边类型不匹配
int *p = &a[0];
指针是一个常量,也就是说指针的指向不能改变;同时,指针是常量,所以必须初始化;
int x = 100;
//int *const p; 错误
//p = &x; 错误
int *const p = &x; //const修饰的是p
int y = 10;
//p = &y 错误
注意
指针常量做函数参数用来交换两个变量的值,保证指针指向不发生改变;
#include <iostream>
using namespace std;
void swap(int *const a, int *const b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int main() {
int a = 10, b = 20;
cout << a << " " << b << endl;
swap(&a, &b);
cout << a << " " << b << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
char * str = "abc";
//char * const str = "abc"; 错误, 为了修改该str的值应该去掉const
cout << str << endl;
//*str = "def"; 错误
str = "def"; //修改字符串常量的值
cout << str << endl;
return 0;
}
指针指向的变量是常量,即不允许通过指针修改指针所指向的内容;
//两种写法
//1. const int *p;
int a = 10, b = 20;
const int *p = &a;
//*p = 30; 无法通过*p来修改它所指向对象的变量 *p的值无法改变
//2. int const *p; const修饰的是*p
注意
存放指针的数组,本质是一个数组,数组中每一个元素是都是指针;
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
int *p[3];
p[0] = &a;
p[1] = &b;
cout << *p[0] << " " << *p[1] << endl;
cout << p[0] << " " << p[1] << endl;
cout << &a << " " << &b << endl;
return 0;
}
指向数组的指针,本质上是一个指针,指针所指向的类型是数组;
#include <iostream>
using namespace std;
int main() {
int a[] = {1, 2, 3};
int (*p)[3];
p = &a;
cout << &a << " " << p << endl;
cout << *p[0] << endl;
return 0;
}
?
int a = 5;
int *q = &a;
int **p = &q;
注意
int * const * p;
//画图说明
#include <iostream>
using namespace std;
typedef int (*p)(int, int);
int process(int a, int b, p func)
{
return func(a, b);
}
int add(int a, int b)
{
return a + b;
}
int main() {
cout << process(3, 4, add);
return 0;
}
指向不明或不当的内存地址。以下三种情况可能导致野指针
//1. 指针未初始化
int *p;
//2. 指针指向的变量被free或delete后没有置空
int *p = (int*)malloc(sizeof(int));
free(p);
//3. 指针操作超过所指向变量的生命周期
原文:https://www.cnblogs.com/Trevo/p/13299916.html