-1

I have a declaration of an array like

int a1[5];

If I declare this array like this:

int *a2;
a2 = malloc(sizeof(int)*5);

and then use it as I would use the array a1 what are the differences. Also if this is done in a function and the function ends both a1 and a2 go out of scope. In case of a1 the memory is released automatically but in case of a2 is it done automatically or would we have to deallocate it using delete?

3
  • 1
    Arrays are not pointers. Pointers are not arrays. You cannot declare one as the other. You can have a pointer pointing into an array, but this has nothing to do with declaring either of them. Commented Apr 29, 2019 at 5:52
  • Thank you for the comment. As a end result of the 2 comparing declarations what is different in the memory map? Please correct me if I am wrong but I am under the impression both type of declarations result in a contiguous memory space of 5 *sizeof(int) storage locations. Hence the question what are the differences? Commented Apr 29, 2019 at 5:57
  • The only thing the second fragment declares is a pointer. What results in a contiguous memory space of 5*sizeof(int) size is not a declaration but a dynamic allocation, which is totally separate from the declaration, has a totally different lifetime from the thing declared, etc. Commented Apr 29, 2019 at 6:07

2 Answers 2

2

When you write

int a[10];

you say

"assign 10 blocks of memory to me each of which can store an integer value".

By default when you put this definition in a block (part of code surrounded by { and }), you cannot use the variable a outside of block.

Why? Suppose the program is executing instructions inside of a block and it came across this definition. It allocates some memory to store the variable a. When the program finds that it has reached the end of block, it destroys the whole memory it has allocated while it was in the block. So, when you refer a in code after the closing brace (}), it doesn't know what a is because the memory was destroyed.

On the other hand when you write

int* a = (int*) malloc(10*(sizeof(int)));

you say

"assign 10 blocks of special memory to me each of which can store an integer value"

. This special memory is called heap memory. It is special because, it is present in a new place that is never destroyed (unless you ask it to). So, you can access it even outside the block.

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

Comments

2

a2's memory won't be deallocated automatically. You can always follow this simple rule of thumb - if you used malloc to allocate it, you need to use free to deallocate it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.