1 声明指针型变量
在声明指针的时候要指明它所指向的数据类型。指向整型(int)或浮点型(float)数据的指针与指向一个字符型(char)数据的指针并不相同
type * pointer_name;
-
type 是指针所指向的数据的类型
Example 1 指针类型指向
#include <iostream>
using namespace std;
int main()
{
int* a;
char* b;
float* c;
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
cout << sizeof(c) << endl;
return 0;
}
它们是3个指针的声明,每一个指针指向不同的数据类型。这3个指针本身其实在内存中占用同样大小的内存空间(指针的大小取决于不同的操作系统),Linux64位操作系统是8字节。但它们所指向的数据是不同的类型,一个是整型(int),一个是字符型(char),还有一个是浮点型(float)
Example 2: 指针类型的转换
#include <stdio.h>
int main()
{
int a=10; char b='a'; float c = 3.14; double d = 3.14159;
int* a_ptr = &a; // 4 bytes
char* b_ptr = &b; // 1 bytes
float* c_ptr = &c; // 4 bytes
double* d_ptr = &d; // 8 bytes
void* ptr;
// void* 可以转换成任意类型指针
int* ptr_int = (int*)ptr;
char* ptr_char = (char*)ptr;
float* ptr_float = (float*)ptr;
double* ptr_double = (double*)ptr;
// int*
char* int_char = (char*)a_ptr;
float* int_float = (float*)a_ptr;
double* int_double = (double*)a_ptr;
// char*
int* char_int = (int*)b_ptr;
float* char_float = (float*)b_ptr;
double* char_double = (double*)b_ptr;
// float*
int* float_int = (int*)c_ptr;
char* float_char = (char*)c_ptr;
double* float_double = (double*)c_ptr;
// double* 自己试
return 0;
}
本质:只是在原有类型的基础上多了一个新的指向类型的功能
例如:原来只能指向int
int* a_ptr = &a;
现在我把这个 int* 当作整体,在外面再给一个 char* 字符指针
char* int_char = (char*)a_ptr;
目的:原来的 int* ,因为我给它赋予了 char* 功能即按字节访问,那我就可以按字节访问的方式去访问 int*,当解引用的时候,自然也会像字符串一样,指向第一个字符;
2 几个符号
&
// 取址
int a = 10;
int* ptr = &a;
// 引用
int a = 10;
int& b = a;
*
// 声明指针
int* ptr;
// 解引用
int a = 10;
int* ptr = &a;
int b = *ptr; // Value pointed by
#include <stdio.h>
int main()
{
int a = 15;
int& b = a;
int c = a;
int* ptr = &a;
// &a 取变量 a 的地址
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", &a);
printf("\n");
// &b 引用,b 相当于是 a 的别名,是同一块内存的数据
printf("Value of b: %d\n", b);
printf("Address of b: %p\n", &b);
printf("\n");
// c 是另外声明的变量,只是把 a 的值赋给 c
printf("Value of c: %d\n", c);
printf("Address of c: %p\n", &c);
printf("\n");
printf("Value of ptr: %p\n", ptr);
printf("Address of ptr: %p\n", &ptr); // & 取 ptr 的内存地址
printf("Value pointed by ptr: %d\n", *ptr); // 取 ptr 指向的值
return 0;
}
通过上面这个例子,希望你可以明白四种赋值方式的区别,以后在看到变量的时候,不仅仅只是看到变量的值,也要关心这个变量的地址。