Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending element into an array of strings in C

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] ?

like image 853
dave_1234 Avatar asked Apr 17 '15 12:04

dave_1234


People also ask

How do you put the elements of a string in an array in C?

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.

Can I add an element to an array in C?

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.

Can you add to a string array?

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.


2 Answers

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" );
like image 109
Vlad from Moscow Avatar answered Sep 30 '22 04:09

Vlad from Moscow


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.

like image 37
Nick Bailey Avatar answered Sep 30 '22 02:09

Nick Bailey