柔性数组:大小待定的数组
- c语言中结构体最后一个元素可以是未知大小的数组
如:
复制代码
1
2
3
4
5
6struct SoftArray { int len; int array[]; //柔性数组,不占用存储空间 };
柔性数组的使用方法:(创建一个大小指定的数组并赋值打印出来)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56#include<stdio.h> #include<stdlib.h> //柔性数组的使用方法 struct SoftArray { int len; int array[]; //柔性数组,不占用存储空间 }; struct SoftArray* create_soft_array(int size) { struct SoftArray* ret = NULL; if(size > 0) { ret = (struct SoftArray*) malloc(sizeof(struct SoftArray) + sizeof(int)*size); ret -> len = size; } return ret; } void delete_soft_array(struct SoftArray* sa) { free(sa); } void func(struct SoftArray* sa) { int i = 0; if(NULL != sa) { for(i = 0; i < sa->len ;i++) { sa->array[i] = i+1; } } } int main(int argc, char const *argv[]) { int i = 0; struct SoftArray* sa = create_soft_array(10); func(sa); for(i = 0;i < sa->len;i++) { printf("%dn", sa -> array[i]); } delete_soft_array(sa); return 0; }
最后
以上就是安静机器猫最近收集整理的关于c语言动态设定数组大小 —— 柔性数组的全部内容,更多相关c语言动态设定数组大小内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复