D
dam_fool_2003
Hai,
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
printf("%d\n",y);
return 0;
}
This is a wrong one and given me a runtime error.
Then what is variable length array?
So I tried the following:
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
{
*y = malloc(sizeof *y);
if(*y == NULL)
exit(EXIT_FAILURE);
else
printf("%d size=%d\n",y,sizeof y);
}
return 0;
}
OUTPUT:
589600 size=12
9 size=12
10 size=12
0 size=12
0 size=12
0 size=12
588632 size=12
11912 size=12
1 size=12
589584 size=12
593160 size=12
…....
…....
….....
…
Even though it gave some warning and runtime error I can see the array
size has changed since I used malloc and allocated with 3 * 4 (C array
starts with zero) so the size = 12.
1)Is my understanding of the above is correct?
2)Is the above program behavior is undefined?
Kindly help.
I studied that the array size is fixed. But I come across a word
called "variable length array". Is it possible to change the array
size? So I tried the following:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
printf("%d\n",y);
return 0;
}
This is a wrong one and given me a runtime error.
Then what is variable length array?
So I tried the following:
int main(void)
{
int y[3] = { 7, 9,10},i;
for (;i<20;i++)
{
*y = malloc(sizeof *y);
if(*y == NULL)
exit(EXIT_FAILURE);
else
printf("%d size=%d\n",y,sizeof y);
}
return 0;
}
OUTPUT:
589600 size=12
9 size=12
10 size=12
0 size=12
0 size=12
0 size=12
588632 size=12
11912 size=12
1 size=12
589584 size=12
593160 size=12
…....
…....
….....
…
Even though it gave some warning and runtime error I can see the array
size has changed since I used malloc and allocated with 3 * 4 (C array
starts with zero) so the size = 12.
1)Is my understanding of the above is correct?
2)Is the above program behavior is undefined?
Kindly help.