很简单利用C语言中的动态数组就可以搞定
举个例子
#include <stdio.h>#include <stdlib.h>
#include <malloc.h>
#include <time.h>
int main()
{
srand((unsigned)time(NULL))
int n
int new_number
printf("please input a number:\n")
scanf("%d",&n)
int *p = (int *)malloc(n*sizeof(int))
for (int i=0i<ni++)
{
p[i] = rand()%100
}
printf("the array is:\n")
for (int i=0i<ni++)
{
printf("%d\t",p[i])
}
printf("add a new number to array:\n")
scanf("%d",&new_number)
int *q = (int *)realloc(p,(n+1)*sizeof(int))
q[n] = new_number
printf("after add a new number the array is:\n")
for (int i=0i<n+1i++)
{
printf("%d\t",q[i])
}
free(q)
system("pause")
return 0
}
通过动态数组就可以在原本已经满的数组后面继续添加元素
把单一数放到数组的末尾,于是每个struct objects可以拥有可变数组的数组。
struct mumble{
/* stuff */
char pc[1]
}
//从文件或标准输入装置中取得一个字符串
//然后为struct 本身和该字符配置足够的内存
struct mumble * pmumbl = (struct mumble*)
malloc(sizeof(struct mumble) + strlen(string) +1)
strcpy(&mumble.pc,string)
首先,结构体的末尾定义了一个char数组,只分配了1个字符。那怎么能说是可变大小数组。
往下看,他用malloc函数分配了一堆的内存。大小为结构体+字符串+1(字符串结束符)如下图所示。
通过strcpy,将string字符串拷贝给mumble.pc,pmumble已经分配了足够的内存,因此只要赋值即可,也就达到了可变大小数组的意思。
但是,C++中的类可不同。
C++中 public、protected、private内的声明顺序可以被保证,但是这三个关键字的布局是不同的。因此总的排列顺序并不能被保证。因此,不能实现struct的可变大小的数组。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)