Differences between Arrays and Pointers
◀ Arrays Versus Pointers▶ Multi-dimensional Array via malloc() Amazon
n array is an allocation of resources during compile time. Upon knowing the size and type of the array, the compiler allocates corresponding resources of that specific size for that specific type. You can NO LONGER
change its size during run time. A pointer, however, exhibits different behavior. C users can specify the size via malloc()
, and C++ users can do so by using the keyword new
A pointer is useful when the programmer does not know in advance the size of the type needed. For example, if you want to write a program that creates however many objects of points specified by user’s command line, you can declare a pointer pointing to point
, then use malloc()
to allocate that many objects once the user enters that number.
Another way a pointer is useful is when you need compiler to see an object which is not initialized by the constructor of that class. For example, you can create a pointer pointing to an object of a class without using its constructor.
If you simply create an object of a class, you need to specify its arguments according to its constructor.
In a situation where you don’t know the arguments of the constructor yet, using a pointer is a good option.
In the first year of programming, I usually used arrays. After I learned C’s malloc()
and C++’s new, I began to rely on dynamic allocation of resources. Dynamic memory allocation is important and below we will see how to use malloc()
◀ Arrays Versus Pointers▶ Multi-dimensional Array via malloc()