0

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;
}
2
  • what error does it give you? Commented Mar 25, 2014 at 0:59
  • "ivalid type argument of '->' (have 'struct saf')" Commented Mar 25, 2014 at 1:01

3 Answers 3

2

exp1 isn't a pointer. Use

exp1.stack = malloc(n);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is it . Thank you so much, what a fool i am
2

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.

1 Comment

It doesn't work,maybe i am missing something. Should i change something in struct?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.