Appending element into an array of strings in C

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.


Hi,

It really depends on what you mean by append.

...
int tab[5]; // Your tab, with given size
// Fill the tab, however suits you.
// You then realize at some point you needed more room in the array
tab[6] = 5; // You CAN'T do that, obviously. Memory is not allocated.

The problem here can be two things :

  • Did you misjudge the size you need ? In that case, just make sure this given size you mentioned is correctly 'given', however that might be.
  • Or don't you know how much room you want at the beginning ? In that case, you''ll have to allocate the memory yourself ! There is no other way you can resize a memory chunk on the fly, if I might say.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define STR_MAX_SIZE 255                                // Maximum size for a string. Completely arbitray.
char *new_string(char *str) { char *ret; // The future new string;
ret = (char *) malloc(sizeof(char) * 255); // Allocate the string strcpy(ret, str); // Function from the C string.h standard library return (ret); }
int main() { char *strings[STR_MAX_SIZE]; // Your array char in[255]; // The current buffer int i = 0, j = 0; // iterators
while (in[0] != 'q') { printf("Hi ! Enter smth :\n"); scanf("%s", in); strings[i] = new_string(in); // Creation of the new string, with call to malloc i++; } for ( ; j < i ; j++) { printf("Tab[ %d ] :\t%s\n", j, strings[j]); // Display free(strings[j]); // Memory released. Important, your program // should free every bit it malloc's before exiting }
return (0); }


This is the easiest solution I could think of. It's probably not the best, but I just wanted to show you the whole process. I could have used the C standard library strdup(char *str) function to create a new string, and could have implemented my own quick list or array.

Tags:

C

Arrays

Append