当前位置:网站首页>[C language] creation and use of dynamic arrays
[C language] creation and use of dynamic arrays
2022-08-09 11:17:00 【XV_】
在C语言中,使用malloc
function to create dynamic arrays,Use a pointer to point to it,使用下标进行访问.
unsigned long *a = (unsigned long *)malloc(2 * sizeof(int));
a[0] = 1000;
a[1] = 2000;
printf("%d %d\n", a[0], a[1]);
free(a);
上述例子,申请了两个intDynamic array of spaces,使用int *
指向它,使用a[0],a[1]
访问,This is the same as array access,The difference is that the dynamic application exists堆空间,还需要使用free
进行释放,And the general array is in the stack space,自动释放.
这个很容易,I would like to extend the analogy here,这是Liunx 0.11A similar piece of code for the kernel is interesting.
#include <stdio.h>
#include <stdlib.h>
typedef struct desc_struct
{
unsigned long a, b;
}
desc_table[256];
desc_table idt, gdt;
void set_gate(unsigned long *gate_addr) {
gate_addr[0] = 100;
gate_addr[1] = 200;
}
int main() {
int size = sizeof(idt) / sizeof(idt[0]); // size = 256
printf("%d\n",size);
printf("%d %d\n", idt[0].a, idt[0].b);
set_gate((unsigned long *)&idt[0]);
printf("%d %d\n", idt[0].a, idt[0].b); // 输出 100 200
return 0;
}
This example is rather strange,strange inaccess to the structure.
main
函数调用了set_gate
函数,并且将idt[0]
The address is passed as a parameterset_gate
函数获取了idt[0]
的地址之后,直接使用下标to access two variables inside the structure
我们知到,General structure variables are used.
,结构体指针使用->
访问,这种使用下标It's kind of weird,我们分析一下.
- The two variables inside the structure are contiguous,都是
unsigned long
类型 - 现在有一个
unsigned long*
指针指向了The first variable in the structure body(By default it points to the beginning)
我们可以看到,对于这种模式,Not a dynamic array嘛,它们的形式是一样的,访问的时候,a和bIt can be accessed through the subscript of the pointer.
另外就是,Because the pointer is obtained,也就是地址,而且还不是结构体指针,Rather, it is a pointer to the type of the element in the struct,所以,There is also no way to access it through the structure.
从底层来说,这种方式是可行的!需要明白,传参之后,Structs are actually functionsset_gate
中是看不见的,是消失的.
边栏推荐
猜你喜欢
golang 三种指针类型具体类型的指针、unsafe.Pointer、uintptr作用
matlab图像分割,从基因芯片荧光图像中提取阴性点(弱)和阳性点(强)
七夕?程序员不存在的~
【VIBE: Video Inference for Human Body Pose and Shape Estimation】论文阅读
富媒体在客服IM消息通信中的秒发实践
ThreadLocal及其内存泄露分析
Jmeter BeanShell post processor
信号量SIGCHLD的使用,如何让父进程得知子进程执行结束,如何让父进程区分多个子进程的结束
Tensorflow realize parameter adjustment of linear equations
信息系统项目的十大管理
随机推荐
激光条纹中心提取——灰度重心法
ICML 2022 | Out-of-Distribution Detection with Deep Nearest Neighbors
1005 Spell It Right (20分)
Getting Started with MNIST Machine Learning
1007 Maximum Subsequence Sum (25分)
matlab fcnchk 函数用法
PTA 换硬币
无刷无霍尔BLCD电机控制
Use gdb to debug multi-process programs, debug parent and child processes at the same time
c语言函数的递归调用(汉诺塔问题,楼梯递归问题等)
Oracle数据库体系结构
gdb 10.2的安装
全网最简单解决OneNote中英字体不统一
The use of C language typedef 】 : structure, basic data types, and array
UNIX Philosophy
verbose np.matmul/np.dot/np.multiply/tf.matmul/tf.multiply/*
C语言中信号函数(signal)的使用
链表基本操作(详解)
CentOS6.5 32bit安装Oracle-11gR2步骤说明
PTA 矩阵运算