about the array in C
I have written a following code (see code comments for the question),
#include<stdio.h>
int main()
{
int size;
scanf("%d",&size);
int arr[size]; /*is it a valid statement?*/
for(int i=1;i<=size;i++)
{
scanf("%d",&arr[i]);
开发者_开发问答printf("%d",arr[i]);
}
return 0;
}
The use of a non constant array size is valid C99 but not C90. There is an older gcc extension allowing it.
Note that taking advantage of this make it harder to check that memory allocation succeed. Using it with values provided by the user is probably not wise.
You cannot allocate a dynamic array in C90 like that. You will have to dynamically allocate it with malloc like this:
int* array = (int*) malloc(sizeof(int) * size);
You also index the arrays starting at 0 not 1, so the for loop should start like this:
for(int i = 0; i < size; i++)
If you use the malloc method, you will also need to free the memory after you're done with it:
free(array);
Also,
Array indexing in C
starts for 0, not from 1. and does not include the size
.
int i;
for(i=0 ; i < size ; i++) // Notice the < and the 0
{
//...
}
The compiler tries to evaluate int arr[size]
at compile time. In this case, arr is allocated on the stack, so the compiler wants to know its size ahead of time. Instead, you need to allocate arr on the heap using malloc
, like this.
#include<stdio.h>
int main()
{
int size;
scanf("%d",&size);
int *arr = malloc(sizeof(int) * size);
for(int i=1;i<=size;i++)
{
scanf("%d",&arr[i]);
printf("%d",arr[i]);
}
free(arr);
return 0;
}
See this post for more information on when to use malloc
This would be valid if size were constant. Otherwise, you should do what DShook said. Additionally, make sure you free(array) at some point, or your program will leak memory.
精彩评论