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;
}
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc.
Syntax to initialize an array:-int numbers[] = {2, 3, 4, 5, 6}; int numbers[] = {2, 3, 4, 5, 6}; int numbers[] = {2, 3, 4, 5, 6}; In case, if you don't specify the size of the array during initialization then the compiler will know it automatically.
An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Five values of type int can be declared as an array without having to declare five different variables (each with its own identifier).
An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With