typedef结构 { struct table **符号; //堆栈的数组 int top; //顶部元素的索引 int size; //堆栈的最大大小 }堆叠;
void *createStack(int size)
{
stack *stck;
stck = (stack *) malloc(sizeof(stack));
stck->symbols = ....
stck->size = size;
stck->top = -1;
printf("stack is created --> size is : %d \n",size);
}
这里我需要分配我的堆栈的符号数组,这是“...”,但我无法弄清楚它的语法,请帮助:)
答案 0 :(得分:4)
malloc(size * sizeof(struct table*));
答案 1 :(得分:3)
(struct table **)malloc(size * sizeof(struct table*));
但是,如果你想一次预先分配所有空间。如果你想要随时分配更多,你可以从小于size
的东西开始,并在你的空间不足时在你的push()函数中分配更多。
答案 2 :(得分:1)
符号是指向结构表的指针的一维数组还是结构表的二维数组?
stck->symbols = malloc(sizeof *(stck->symbols) * numberOfElements);
表示numberOfElements
的任何值。鉴于stck->符号的类型为struct table **
,表达式*(stck->symbols)
的类型将为struct table *
。你也可以写
malloc(sizeof (struct table*) * numberOfElements);
但我更喜欢前一种方法,因为它最大限度地减少了你必须记住类型的地方数量。
由于这是C,你不需要投射malloc()
的结果,这被认为是不好的做法;如果您忘记包含stdlib.h或者在范围内没有malloc()
的原型,那么演员将会发出警告,提醒您注意问题(尽管由于C99不再允许隐式int类型,因此可能没有更长的问题)。
答案 3 :(得分:0)
stck->symbols = baseaddress = malloc(...required total size...);
int nextDataLocation = baseAddress + numberOfRows*sizeof(void*);
for(int i=0; i<numberOfLines; i++)
{
stck->symbols[i] = nextDataLocation;
..copy string i to address stck->symbols[i]...
nextDataLocation += lengthOfString[i];
}