Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about the array in C

Tags:

arrays

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;
}
like image 655
nobalG Avatar asked Apr 13 '11 16:04

nobalG


People also ask

What is array in C and its types?

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.

What is array in C with syntax and example?

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.

What is array with syntax?

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).

What is array explain its?

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.


2 Answers

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.

like image 200
AProgrammer Avatar answered Oct 27 '22 00:10

AProgrammer


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);
like image 31
DShook Avatar answered Oct 26 '22 23:10

DShook