Reputation: 151
Maybe this question is answered somewhere but i can't find it. I want to declare global array. But the size of this array depends on my input.How do i do that ?, Thank you
Idea is:
char* array[maxsize];
int main(){
int maxsize;
scanf("%d",&maxsize);
}
EDIT: What if an array is 2D array ?
Upvotes: 2
Views: 25572
Reputation: 21609
Use calloc
like so
#include <stdio.h>
#include <stdlib.h>
char* array=NULL;
int main()
{
int maxsize;
scanf("%d",&maxsize);
array = calloc(maxsize, sizeof(char));
free(array);
array = NULL;
}
This dynamically allocates maxsize
chars on the applications heap. Note that a call to free
is required to release the dynamic allocation. If this is not done it's called a memory leak. In this trivial program though its not too serious if free is not called.
Ok so technically its not an array its a pointer but the two are mostly interchangeable. Using calloc
for a char array is a good idea, as all values are initialised to 0 and if you copy some string in there its already zero terminated.
Upvotes: 2
Reputation: 489
What you're talking about is known as dynamic allocation and it's done a little differently to the normal allocation (which happens is a different part of memory), to do this in C you use a function from stdlib.h (remember to #include it) called calloc which takes two arguments the number of elements and the size of each element, so assuming you want an array of chars the code would look something like this:
char *array;
int main(void)
{
int maxsize;
scanf("%d", &maxsize);
array = calloc(maxsize, sizeof(char));
}
you'll notice that there is no [] after the declaration of array, that's because it is not an array but rather a pointer, but no fear you can still access indices like an array. So array[1] will still work provided you have at least 2 elements in the array.
Upvotes: 0