0

If I have a variable called Tree * myTree, how could could I put this variable into an array of Tree*?

For example, I want to do something like:

Tree *allTrees[10];
allTrees = malloc(sizeof(Tree) * 10;
for (int i = 0; i < 10;i++)
{
    allTrees[i] = malloc(sizeof(Tree));
}
allTrees[0] = myTree;

What am I doing wrong here?

5
  • what is the error? Commented Jul 29, 2016 at 23:24
  • 1
    @WhozCraig: And the question remains: what is the error? Specifically the compiler's error message should be included in the question. (I'm sure you know this; I'm prodding the OP.) Commented Jul 29, 2016 at 23:28
  • @KeithThompson I just realized its moot (the missing paren) regardless. Your comment in Byteventeurer's answer below is the real issue. Commented Jul 29, 2016 at 23:29
  • @WhozCraig: I hadn't even notice the missing ) (chuckle) Commented Jul 29, 2016 at 23:30
  • If you're confused about arrays and pointers, read section 6 of the comp.lang.c FAQ. Commented Jul 29, 2016 at 23:31

1 Answer 1

1

You don't need to do

allTrees = malloc(sizeof(Tree) * 10);

because you are already allocating the array on the stack:

Tree *allTrees[10];

The rest should be fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Not only don't you need to, you can't. allTrees is an array, and you can't assign to an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.