How to create user define array structure of n size in c language

146 Views Asked by At

I want to create a 'n' size of array structure but I don't know how to do it. I always create static like this

typedef struct
{
  int id;
  char name[25];
  char dob[11];
}info;
info student[5];

here i want it info student[n] but it doesn't work because it takes only integer.

1

There are 1 best solutions below

4
Vlad from Moscow On

It seems you mean the following code

typedef struct
{
  int id;
  char name[25];
  char dob[11];
}info;
info student[n];

where n is some variable of an integer type.

This declaration of an array declares a variable length array. Variable length arrays may have only automatic storage duration . So you may declare such an array in a function as for example

typedef struct
{
  int id;
  char name[25];
  char dob[11];
}info;

int main( void )
{
    size_t n;

    printf( "Enter the array size: " );
    scanf( "%zu", &n );

    info student[n];
    //...
}

You may not declare a variable length array in a file scope.

Pay attention to that the value of the variable n shall be a positive number. Another peculiarity is that you may not initialize elements of a variable length array in its declaration.

If your compiler does not support variable length arrays then you need to allocate an array of structures dynamically like for example

typedef struct
{
  int id;
  char name[25];
  char dob[11];
}info;

int main( void )
{
    size_t n;

    printf( "Enter the array size: " );
    scanf( "%zu", &n );

    info *student = malloc( n * sizeof( *student ) );
    //...
}