So I’m studying memory allocation and it said that you can only allocate memory dynamically using malloc(); but isn’t this dynamic memory allocation too? it works btw.So I’m a bit confused.
#include<stdio.h>
#include<conio.h>
int main()
{
int integer,cntr;
scanf("%d",&integer);
char words[integer];
for(cntr = 0;cntr < integer - 1;cntr++)
words[cntr] = 'k';
words[cntr] = '\0';
printf("%s",words);
getch();
return(0);
}
That’s a variable-length array. The size is indeed dynamic, but in practice it’ll generally be allocated on the stack instead of the heap (so don’t use it for anything too big).
Depending on your compiler and so on, this will probably end up being a lot faster than allocating heap memory, being nothing but an adjustment of the stack pointer.
Variable-length arrays were introduced in the C99 standard, so bear in mind that you won’t be able to use them with very old C compilers (such as MSVC).