I have an array of strings with a given size, without using any memory allocation, how do I append something into it?
Say I run the code, its waiting for something you want to enter, you enter "bond"
, how do I append this into an array ? A[10] ?
To add a new element ie. a character, to the end of a string, move to the NULL character & replace it with the new character, then put back the NULL after it. This assumes that sufficient space is already available for the new character.
We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array. After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.
You can also add an element to String array by using ArrayList as an intermediate data structure. An example is shown below. As shown in the above program, the string array is first converted into an ArrayList using the asList method. Then the new element is added to the ArrayList using the add method.
If the array declared like
char A[10];
then you can assign string "bond" to it the following way
#include <string.h>
//...
strcpy( A, "bond" );
If you want to append the array with some other string then you can write
#include <string.h>
//...
strcpy( A, "bond" );
strcat( A, " john" );
You can't append to an array. When you define the array variable, C asks the is for enough contiguous memory. That's all the memory you ever get. You can modify the elements of the array (A[10]=5) but not the size.
However, you CAN create data structures that allow appending. The two most common are linked lists and dynamic arrays. Note, these are no built into the language. You have to implement them yourself or use a library. The lists and arrays of Python, Ruby and JavaScript are implemented as dynamic arrays.
LearnCThHardWay has a pretty good tutorial on linked lists, though the one on dynamic arrays is a little rough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With