当前位置:网站首页>c语言指针深入理解
c语言指针深入理解
2022-07-05 09:10:00 【不秃头的萧哥】
文章目录
前言
指针是c语言中较难理解的知识点了,也非常重要,今天我们就来一起深入理解指针吧
一、指针的概念
- 指针就是个地址,地址唯一标识一块内存空间。(常说的指针指的是指针变量)
- 指针的大小是固定的4/8个字节(32位平台/64位平台)。
- 指针是有类型,指针的类型决定了指针的±整数的步长,指针解引用操作的时候的权限。
- 指针的运算:指针相减为两指针之间的元素个数,指针+整数为指针
二、字符指针
在指针的类型中我们知道有一种指针类型为字符指针 char*
一般使用:
int main()
{
char ch = 'w';
char *pc = &ch;
*pc = 'w';
return 0;
}
还有一种使用方式如下:
int main()
{
const char* pstr = "hello bit.";//这里是把一个字符串放到pstr指针变量里了吗?
printf("%s\n", pstr);
return 0;
}
代码 const char* pstr = "hello bit."特别容易让人以为是把字符串 hello bit 放到字符指针 pstr 里了,但是本质是把字符串 hello bit. 首字符的地址放到了pstr中。
有这样一道面试题:
#include <stdio.h>
int main()
{
char str1[] = "hello bit.";
char str2[] = "hello bit.";
const char *str3 = "hello bit.";
const char *str4 = "hello bit.";
if(str1 ==str2)
printf("str1 and str2 are same\n");
else
printf("str1 and str2 are not same\n");
if(str3 ==str4)
printf("str3 and str4 are same\n");
else
printf("str3 and str4 are not same\n");
return 0;
}
输出结果是:
这里str3和str4指向的是一个同一个常量字符串。C/C++会把常量字符串存储到单独的一个内存区域,当几个指针。指向同一个字符串的时候,他们实际会指向同一块内存。但是用相同的常量字符串去初始化
不同的数组的时候就会开辟出不同的内存块。所以str1和str2不同,str3和str4不同。
二、指针数组
指针数组顾名思义就是存放指针的数组
int* arr1[10]; //整形指针的数组
char *arr2[4]; //一级字符指针的数组
char **arr3[5];//二级字符指针的数组
三、数组指针
1.数组指针的定义
数组指针顾名思义就是指向数组的指针
int *p1[10];
int (*p2)[10];
//p1, p2分别是什么?
int (*p)[10];
//
//
解释:p先和*结合,说明p是一个指针变量,然后指着指向的是一个大小为10个整型的数组。所以p是一个指针,指向一个数组,叫数组指针。
这里要注意:[]的优先级要高于*号的,所以必须加上()来保证p先和*结合。
2. &数组名和数组名
对于下面的数组:
int arr[10];
arr 和 &arr 分别是啥?
我们知道arr是数组名,数组名表示数组首元素的地址。
那&arr数组名到底是啥?
我们看一段代码:
#include <stdio.h>
int main()
{
int arr[10] = {
0};
printf("%p\n", arr);
printf("%p\n", &arr);
return 0;
}
运行结果如下:
可见数组名和&数组名打印的地址是一样的。
难道两个是一样的吗?
我们再看一段代码:
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
printf("arr = %p\n", arr);
printf("&arr= %p\n", &arr);
printf("arr+1 = %p\n", arr+1);
printf("&arr+1= %p\n", &arr+1);
return 0;
}
根据上面的代码我们发现,其实&arr和arr,虽然值是一样的,但是意义应该不一样的。
实际上: &arr 表示的是数组的地址,而不是数组首元素的地址。
本例中 &arr 的类型是: int(*)[10] ,是一种数组指针类型
数组的地址+1,跳过整个数组的大小,所以 &arr+1 相对于 &arr 的差值是40
3. 数组指针的使用
那数组指针是怎么使用的呢?
既然数组指针指向的是数组,那数组指针中存放的应该是数组的地址。
看代码:
#include <stdio.h>
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,0};
int (*p)[10] = &arr;//把数组arr的地址赋值给数组指针变量p
//但是我们一般很少这样写代码
return 0
}
在二维数组传参时,就可以将参数设置为数组指针的形式
四、数组参数、指针参数
在写代码的时候难免要把【数组】或者【指针】传给函数,那函数的参数该如何设计呢?
1. 一维数组传参
#include <stdio.h>
void test(int arr[])
{
}
void test(int arr[10])
{
}
void test(int *arr)
{
}
void test2(int *arr[20])
{
}
void test2(int **arr)
{
}
int main()
{
int arr[10] = {
0};
int *arr2[20] = {
0};
test(arr);
test2(arr2);
}
2. 二维数组传参
void test(int arr[3][5])
{
}
void test(int arr[][5])
{
}
void test(int (*arr)[5])
{
}
int main()
{
int arr[3][5] = {
0};
test(arr);
}
五、 函数指针
首先看一段代码:
#include <stdio.h>
void test()
{
printf("hehe\n");
}
int main()
{
printf("%p\n", test);
printf("%p\n", &test);
return 0;
}
输出的结果:
输出的是两个地址,这两个地址是 test 函数的地址。
那我们的函数的地址要想保存起来,怎么保存?
下面我们看代码:
void test()
{
printf("hehe\n");
}
//下面pfun1和pfun2哪个有能力存放test函数的地址?
void (*pfun1)();
void *pfun2();
pfun1可以存放。pfun1先和*结合,说明pfun1是指针,指针指向的是一个函数,指向的函数无参数,返回值类型为void。
阅读两段有趣的代码:
//代码1
(*(void (*)())0)();
//代码2
void (*signal(int , void(*)(int)))(int);
这两个代码来源于《c陷阱和缺陷》
代码1:
(void(*)( ) )在0的前面,函数指针类型就是void(*)( ),
由此可知,这个是将0强制类型转换成函数指针,并解引用
代码2:
将代码2简化一下就较为清晰了
typedef void(*pfun_t)(int);
pfun_t signal(int, pfun_t);
六、 函数指针数组
数组是一个存放相同类型数据的存储空间,那我们已经学习了指针数组,
比如:
int *arr[10];
//数组的每个元素是int*
那要把函数的地址存到一个数组中,那这个数组就叫函数指针数组,那函数指针的数组如何定义呢?
int (*parr1[10])();
int *parr2[10]();
int (*)() parr3[10];
答案是:parr1
parr1 先和 [] 结合,说明 parr1是数组,数组的内容是什么呢?
是 int (*)() 类型的函数指针。
七、指向函数指针数组的指针
指向函数指针数组的指针是一个指针
指针指向一个数组 ,数组的元素都是函数指针 ;
如何定义?
void test(const char* str)
{
printf("%s\n", str);
}
int main()
{
//函数指针pfun
void (*pfun)(const char*) = test;
//函数指针的数组pfunArr
void (*pfunArr[5])(const char* str);
pfunArr[0] = test;
//指向函数指针数组pfunArr的指针ppfunArr
void (*(*ppfunArr)[5])(const char*) = &pfunArr;
return 0;
}
八、 回调函数
回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
首先演示一下qsort函数的使用:
#include <stdio.h>
//qosrt函数的使用者得实现一个比较函数
int int_cmp(const void * p1, const void * p2)
{
return (*( int *)p1 - *(int *) p2);
}
int main()
{
int arr[] = {
1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
int i = 0;
qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof (int), int_cmp);
for (i = 0; i< sizeof(arr) / sizeof(arr[0]); i++)
{
printf( "%d ", arr[i]);
}
printf("\n");
return 0;
}
使用回调函数,模拟实现qsort(采用冒泡的方式)。
#include <stdio.h>
int int_cmp(const void * p1, const void * p2)
{
return (*( int *)p1 - *(int *) p2);
}
void _swap(void *p1, void * p2, int size)
{
int i = 0;
for (i = 0; i< size; i++)
{
char tmp = *((char *)p1 + i);
*(( char *)p1 + i) = *((char *) p2 + i);
*(( char *)p2 + i) = tmp;
}
}
void bubble(void *base, int count , int size, int(*cmp )(void *, void *))
{
int i = 0;
int j = 0;
for (i = 0; i< count - 1; i++)
{
for (j = 0; j<count-i-1; j++)
{
if (cmp ((char *) base + j*size , (char *)base + (j + 1)*size) > 0)
{
_swap(( char *)base + j*size, (char *)base + (j + 1)*size, size);
}
}
}
}
int main()
{
int arr[] = {
1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };
//char *arr[] = {"aaaa","dddd","cccc","bbbb"};
int i = 0;
bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof (int), int_cmp);
for (i = 0; i< sizeof(arr) / sizeof(arr[0]); i++)
{
printf( "%d ", arr[i]);
}
printf("\n");
return 0;
}
结语
今天我们深入了解了c语言指针的一些相关概念,下一次我将用一些题目来加深对指针的理解。
每天学一点,时间久了,菜鸟也能变成大神
边栏推荐
- Uni app implements global variables
- np. allclose
- [beauty of algebra] solution method of linear equations ax=0
- Applet global style configuration window
- Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
- 信息与熵,你想知道的都在这里了
- asp. Net (c)
- 2310. The number of bits is the sum of integers of K
- Editor use of VI and VIM
- 深入浅出PyTorch中的nn.CrossEntropyLoss
猜你喜欢
My experience from technology to product manager
Install the CPU version of tensorflow+cuda+cudnn (ultra detailed)
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
AUTOSAR从入门到精通100讲(103)-dbc文件的格式以及创建详解
[code practice] [stereo matching series] Classic ad census: (4) cross domain cost aggregation
Ros- learn basic knowledge of 0 ROS - nodes, running ROS nodes, topics, services, etc
Introduction Guide to stereo vision (5): dual camera calibration [no more collection, I charge ~]
Solutions of ordinary differential equations (2) examples
Introduction Guide to stereo vision (1): coordinate system and camera parameters
Priority queue (heap)
随机推荐
Blue Bridge Cup provincial match simulation question 9 (MST)
Causes and appropriate analysis of possible errors in seq2seq code of "hands on learning in depth"
2309. 兼具大小写的最好英文字母
Configuration and startup of kubedm series-02-kubelet
Confusion matrix
AUTOSAR from getting started to mastering 100 lectures (103) -dbc file format and creation details
2311. 小于等于 K 的最长二进制子序列
迁移学习和域自适应
The combination of deep learning model and wet experiment is expected to be used for metabolic flux analysis
Meta tag details
Beautiful soup parsing and extracting data
Talking about label smoothing technology
Information and entropy, all you want to know is here
[daiy4] copy of JZ35 complex linked list
C # draw Bezier curve with control points for lattice images and vector graphics
Use and programming method of ros-8 parameters
Programming implementation of ROS learning 6 -service node
Jenkins pipeline method (function) definition and call
It's too difficult to use. Long articles plus pictures and texts will only be written in short articles in the future
np. allclose