views:

130

answers:

4

Hi all,

typedef struct
{
  struct table **symbols; // array of the stack
  int top; //index of the top element
  int size; //maximum size of the stack
}stack;

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);
}

Here I need to allocate my stack's symbol array which is "..." but I couldn't figure out it's syntax, pls help : )

+4  A: 
malloc(size * sizeof(struct table*));
Thomas Padron-McCarthy
Might be desired to include the cast.
Skurmedel
No in C explicit cast is not required.
Prasoon Saurav
My bad :)... it's just me that likes to be explicit then.
Skurmedel
@Skurmedel: :)........
Prasoon Saurav
Explicitly casting the return value of malloc in C can hide errors (such as neglecting to #include stdlib.h). Avoid doing it.
jamesdlin
+3  A: 
(struct table **)malloc(size * sizeof(struct table*));

But that's if you want to pre-allocate all the space at once. If you want to allocate more as you go, you could start with something smaller than size and allocate more in your push() function when you run out of space.

Seth
+1  A: 

Is symbols intended to be a 1-d array of pointer to struct table or a 2-d array of struct table?

stck->symbols = malloc(sizeof *(stck->symbols) * numberOfElements);

for whatever value of numberOfElements. Given that the type of stck->symbols is struct table **, the type of the expression *(stck->symbols) will be struct table *. You could also write

malloc(sizeof (struct table*) * numberOfElements);

but I prefer the former method, as it minimizes the number of places you have to remember the type.

As this is C, you do not need to cast the result of malloc(), and it's considered poor practice to do so; if you forget to include stdlib.h or otherwise don't have a prototype for malloc() in scope, the cast will supress a warning alerting you to the problem (although since C99 no longer allows implicit int typing, that may no longer be an issue).

John Bode
A: 
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];
}
Pavel Radzivilovsky