Question

I have a struct and an dynamic array inside the struct. I want to malloc this array but i don't really now how. I want that array void because i want the members of this array to be structs. As you can see i tried something but it doesn't really work

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct saf 
{
  int head;
  void **stack;
  int size;
}exp1;



void init(int n)
{

   struct saf exp1->stack = malloc(n);

}

int main()
{

 printf("Give size: ");
 scanf("%d",&exp1.size);
 init(exp1.size);

return 0;
}
Was it helpful?

Solution

exp1 isn't a pointer. Use

exp1.stack = malloc(n);

OTHER TIPS

I believe you are looking for void *, e.g.,

void init (int n)
{
    exp1->stack = malloc(sizeof(void *) * n);
}

You will have to cast it when you use it.

struct saf exp1.stack = malloc(n);

The above statement creates array of n memory locations and returns the void * pointer to the starting address. In this case stack should be single pointer i,e void *stack; If you want stack to be a double pointer i,e void **stack then you should use

exp1.stack=malloc(sizeof(void *)*n);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top