当前位置:网站首页>[C language] creation and use of dynamic arrays

[C language] creation and use of dynamic arrays

2022-08-09 11:17:00 XV_

在C语言中,使用mallocfunction 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.

  1. main函数调用了set_gate函数,并且将idt[0]The address is passed as a parameter
  2. set_gate函数获取了idt[0]的地址之后,直接使用下标to access two variables inside the structure

我们知到,General structure variables are used.,结构体指针使用->访问,这种使用下标It's kind of weird,我们分析一下.

  1. The two variables inside the structure are contiguous,都是unsigned long类型
  2. 现在有一个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中是看不见的,是消失的.

原网站

版权声明
本文为[XV_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091103199296.html