I have a char array
char *data[]= {"11", "22", "33", "44", "55"};
How can I add some extra items to it in the end? data[]="66";
I’d like a dynamic array in C.
Thanks
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 created using the
[]syntax are not dynamic, the length is set at compile-time and cannot change.UPDATE: Actually, C99 adds so-called “variable-length arrays”, which can get their length at run-time. After they’ve been initialized, however, they can’t shrink or expand so the below still applies.
However, an array is trivially expressed when you have pointers: an array can be represented as a pointer to the first element, and a length.
So, you can create a new array by dynamically allocating memory using
malloc():You cannot use the
{}list of elements here, that’s only usable when initializing arrays declared using the[]syntax.To grow the array, you can use the
realloc()function to re-allocate the memory and copy the old values over:Note that every time you call
malloc()(orrealloc()), it can returnNULLif it failed to allocate the requested block. That’s why theifstatements are needed. I cut the initial size down a bit from your example to reduce the number of assignment-lines needed, to make the example shorter.To make the above more efficient, typical dynamical array code uses two length values: one for the actual array (how many values are in the array right now) and one for the memory (how many values to we have room to store). By making the latter value grow in chunks, the total number of memory allocations can be cut down a bit, at the cost of some memory of course.