当前位置:网站首页>[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
中是看不见的,是消失的.
边栏推荐
猜你喜欢
随机推荐
MATLAB代码实现三次样条插值
PTA 换硬币
Oracle数据库的两种进入方式
linux mysql操作的相关命令
C语言数组题_校门外的树_标记法
为什么组合优先于继承
程序员的专属浪漫——用3D Engine 5分钟实现烟花绽放效果
golang 三种指针类型具体类型的指针、unsafe.Pointer、uintptr作用
log4net使用指南(winform版,sqlserver记录)
x86异常处理与中断机制(3)中断处理过程
STemwin中GUI_Exec和GUI_Delay
margin出bug---margin失效
性能测试(01)-jmeter元件-线程组、调试取样器
vite的原理,手写vite
ACM01背包问题
Quartz分布式实现
Missing URI template variable ‘employeeNumber‘ for method parameter of type String
wait系统调用
实现strcat函数
ICML 2022 | Out-of-Distribution Detection with Deep Nearest Neighbors