Adding to an array in C
You cannot add an array. When you define an array variable, C asks that there is enough contiguous memory. This is all the memory you have ever received. You can change the elements of the array (A [10] = 5), but not the size.
However, you can create data structures that allow you to add. The two most common are linked lists and dynamic arrays. Please note: they are not built into the language. You have to implement them yourself or use a library. Python, Ruby and JavaScript lists and arrays are implemented as dynamic arrays.
LearnCThHardWay has a pretty good tutorial on linked lists, although one of the dynamic arrays is a little crude.
source to share
Hello,
It really depends on what you mean by adding.
...
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:
- Have you misjudged the size you want? In this case, just make sure that the size you specified is correct, however it may be.
- Or don't you know how much space you want at the beginning? In this case, you will have to allocate memory yourself! There is no other way to resize a chunk of memory on the fly, so to speak.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_MAX_SIZE 255
// . .
char * new_string (char * str) { char * ret;// ; ret = (char *) malloc (sizeof (char) * 255);// strcpy (ret, str);// C string.h return (ret); }
int main() { char * [STR_MAX_SIZE];// char [255];// int = 0, j = 0;//
( [0]!= 'q') { printf ( "! smth:\n" ); scanf ( "% s", in); [i] = new_string (in);// malloc ++; } for (; j < i; j ++) { printf ( "Tab [% d]:\t% s\n", j, [j]);// ( [J]);// . , // malloc }
return (0); }
code>
This is the easiest solution I could think of. This is probably not the best, but I just wanted to show you the whole process. I could use the C standard library function strdup(char *str)
to create a new line, and I could implement my own quick list or array.
source to share