iva123
iva123

Reputation: 3515

array of pointers allocation

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 : )

Upvotes: 1

Views: 354

Answers (4)

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

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

Upvotes: 0

Seth
Seth

Reputation: 5740

(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.

Upvotes: 4

John Bode
John Bode

Reputation: 123458

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).

Upvotes: 1

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

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

Upvotes: 4

Related Questions