can realloc Array, then Why use pointers?

By : iankits
Source: Stackoverflow.com
Question!

This was an job placement interview I faced. They asked whether we can realloc Array, I told yes. Then They asked - then why we need pointers as most of the people give reason that it wastes memory space. I could not able to give satisfactory answer. If any body can give any satisfactory answer, I'll be obliged. Please mention any situation where the above statement can contradict.

Thank you.

By : iankits


Answers
You can only reallocate an array that was allocated dynamically. If it was allocated statically, it cannot be reallocated [safely].*

Pointers hold addresses of data in memory. They can be allocated, deallocated, and reallocated dynamically using the new/delete operators in C++ and malloc/free in C.

I would strongly suggest that you read The C Programming Language by Kernighan and Ritchie and a solid C++ text like C++ From the Ground Up by Herbert Schildt.

Using dynamic memory, pointers, offsets, etc are all fundamental to using these two languages. Not knowing how they work, and why they exist will be a likely reason for potential employers to turn you down.

*the compiler shouldn't let you reallocate anything that's been allocated statically, but if it does, the behavior is undefined

By : warren


The phrasing is a bit strange, but to me it seems like the interview question was an open ended question designed to get you to explain what you know about arrays, pointers, dynamic memory allocation, etc. If I was the interviewer I'd want the candidate to articulate the differences between int *a = malloc(10 * sizeof(int)); and int a[10];. The followup question is not worded very well, but it was probably an attempt at nudging the candidate in the direction of the difference between a pointer and an array and setting off the train of thought.



OK. You can't realloc an array that has been statically declared. The purpose of using pointers (instead of statically declared array), would be so that you can realloc the space. I guess, to be technically correct, you could realloc a statically defined array by passing a pointer to it, but I wouldn't want to. The behavior is undefined if the pointer is to memory that wasn't allocated by malloc.



This video can help you solving your question :)
By: admin