The allocation by malloc()
is equal to array from the point of view of the question, it is all continuous, when allocating a data sequence.
Well, physically it may not be so because of the virtual memory, but this doesn’t matter for your program, it will see the addresses as if they were continuous.
What changes is the storage location, the malloc()
will allocate in the heap and the array will allocate in the stack (unless it is part of another structure that heap, because there the array is not actually allocating, is just reserving space in another structure). Technically the `stack* is a data structure, so the array is always reserving space. It is true that the heap also, but the structure is external to the application, so it really is an allocation.
If you’re making isolated allocations, there’s no guarantee where each of them will be accessed, so they might be spread out, even though it’s likely that it’s not, in most simple situations, which can lead to error because people don’t care about doing the right thing, just make it work, that are very different things.
This code doesn’t seem to make sense. I think that’s all you want:
Node *lista = malloc(sizeof(Node) * 7);
But if it does:
for (int i = 1; i < n; i++) Node no[i] = malloc(sizeof(Node));
I put in the Github for future reference.
No longer guarantees that the allocation will be continuous.
If you’re making a linked list, then probably want something else, but also different from what is in the question.
There are several ways to allocate memory, depending on what you need.
Study:
I didn’t answer the rest because they are other questions, ask separately. Including because they don’t have enough information to answer.
Guys, just one correction : Forget that one over there, I just wanted to allocate 7 spaces anyway, I don’t know why I did one over there.
– Snow