Gavin
Gavin

Reputation: 2824

Declaring an 2 dimensional array with size according to input

Say, I want an array of words that is of max length 20. I get the number of words to be stored from user input. What is the most memory efficient way to declare the above array?

I could do something like this, but I guess its not very memory efficient?

char wordArray[1000][20];

That is I want "1000" to varies accordingly to user's input. And I can't do this.

int main()
{
    int size;
    printf("Enter size: ");
    scanf("%d", &size);
    char wordArray[size][20];
}

Upvotes: 0

Views: 71

Answers (2)

haccks
haccks

Reputation: 106012

Generally stack size is small and you can't allocate such a big amount of memory on stack. Doing so will result in stack overflow. You need dynamic allocation.

int size;
printf("Enter size: ");
scanf("%d", &size);
char **wordArray = malloc(size*sizeof(char *));

for(int i = 0; i < size; i++)
     wordArray[i] = malloc(20);  

Call free to deallocate.

But, note that this will allocate defragmented memory instead of continuous unlike as in case of 2D array. To get continuous memory allocation you can use pointer to array as

int (*wordArray)[20] = malloc(size * sizeof(*wordArray));  

and access the element as wordArray[i][j].

For more detailed explanation read c-faq 16.6: How can I dynamically allocate a multidimensional array?

Upvotes: 4

Michał Szydłowski
Michał Szydłowski

Reputation: 3409

Nope, it is not, because you're imposing an allocation of 100000 times sizeof(char) of memory. And no, you can't do as you wrote here, because during the compile-time the size of array is unknown, so space cannot be allocated. You could do it using malloc.

Upvotes: 2

Related Questions