Can I write a variable sized array using the following code?
I have executed it on Fedora. I used a pointer a
and integer b
to create the array,
so can I say that this array is a dynamic array?
main()
{
int * const a;
int b;
a[b];
b=5;
int i;
for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
}
No, you can't create variable-length array using this code. When you use
int b;
b
can have any value. It can be 0, 4294967295, or any other number. Then, when you use
a[b];
a
can have any random length each time use execute the program.
Next thing:
a
will not change it's size when you change b
value:
int b = 5;
int a[b];
b = 6;
// Length of `a` is still 5.
If you want to change size of array after it's been created, you should read about malloc()
and realloc()
functions and use them.