About an array in C

I wrote the 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;
}
+5
source share
5 answers

Using the size of a non-persistent array is valid C99, but not C90. There is an older gcc extension allowing it.

Note that using this makes it difficult to verify that the memory allocation is correct. Using it with values ​​provided by the user is probably unreasonable.

+6
source

You cannot allocate a dynamic array in the C90 like this. You will have to dynamically allocate it using malloc as follows:

int* array = (int*) malloc(sizeof(int) * size);

You also index arrays starting with 0, not 1, so the for loop should start like this:

for(int i = 0; i < size; i++)

malloc, , :

free(array);
+4

,

C 0, 1. size.

int i;
for(i=0 ; i < size ; i++) // Notice the < and the 0
{
     //...
}
+3

int arr[size] . arr , . arr , malloc, .

#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;
}

, malloc

. .
0

, . , DShook. , , () - , .

0

All Articles