Yes, you can use the functions calloc, malloc and realloc to dynamically allocate memory from the heap at runtime. <br>
<br>
For example, you can read the size of the array from the user and use this to dynamically allocate space for the array.<br>
<br>
int size;<br>
char *buf;<br>
<br>
scanf("%d", &size);<br>
<br>
buf = (char *)malloc(sizeof(char) * size);<br>
<br>
if ( buf != NULL ) {<br>
...<br>
...<br>
...<br>
}<br>
<br>
...<br>
...<br>
...<br>
<br>
free(buf);<br>
<br>
malloc and calloc allocate a chunk of memory from the heap at runtime. when you are done using this chunk you should always free it as shown above. There is another function which you will find useful and that is realloc. Realloc takes a pointer to a chunk of heap memory and changes the size. So you can allocate more space to an already allocated array. The same holds true here, free it once you are done using it otherwise you will have a memory leak in your program.<br>
<br>
<br>
<br>
Yes , at run time you will have to calculate the length of the memory to be allocated.For eg. <br>
If at run time you come to know that you need to have a character array of 20 bytes. Do :<br>
char *ptr;<br>
ptr = (char*) malloc(sizeof(char) * 20);<br>
<br>
Similarly you can create a 2-d , 3-dimensional or multi-dimensional array dinamically.<br>
<br>
Does it answer your question ?<br>
<br>
Thanx<br>
Siddhartha Singh<br>
<A HREF="mailto:ssingh@aztecsoft.com">ssingh@aztecsoft.com</A><br>
You don't require to define the array(struct array in this case) as static and then malloc it .Either you first declare it as dynamic and then allocate memory from heap dynamically or declare it to be static and then use it without allocating memory using malloc .
hope this helps .
Arun
By itself, arrays in C are not dynamic and never will be. O yes there are those local variables and thus local arrays that are allocated dynamically, whenever a routine starts, but you should recognize that, IN THE MIDDLE OF THE ROUTINE, you cannot just suddenly change the size of an array. You really DO need to simulate it. There is no way in ANSI C's grammar for you to declare a truly dynamic variable or array. C++ is another story...
Fortunately we can easily simulate a dynamic array in C. For one thing, C makes little distinction between arrays and pointers. Since we are using a pointer to store the address of the piece of memory we are using as a dynamic array, we can use it as if it were the array itself. In the above example, you can refer to test[0].number, test[1].number, test[n].number and the compiler will generate correct code. Care must be taken of course, because the compiler cannot know the limits of the array.
"Information has a tendency to be free. Which means someone will always tell you something you don't want to know."
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.