If we can use pointers and malloc to create and use arrays, why does the array type exist in C? Isn’t it unnecessary if we can use pointers instead?
If we can use pointers and malloc to create and use arrays, why does
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Arrays are faster than dynamic memory allocation.
Arrays are “allocated” at “compile time” whereas malloc allocates at run time. Allocating takes time.
Also, C does not mandate that
malloc()and friends are available in free-standing implementations.Edit
Example of array
Example of
malloc()In the array version, the space for the
deckarray was reserved by the compiler when the program was created (but, of course, the memory is only reserved/occupied when the program is being run), in themalloc()version, space for thedeckarray has to be requested at every run of the program.Arrays can never change size, malloc’d memory can grow when needed.
If you only need a fixed number of elements, use an array (within the limits of your implementation).
If you need memory that can grow or shrink during the running of the program, use
malloc()and friends.