Arrays de longitud variable en C/C++

Las arrays de longitud variable también se conocen como arrays de tiempo de ejecución o de tamaño variable . El tamaño de dichas arrays se define en tiempo de ejecución. 

Los tipos modificados de forma variable incluyen arrays de longitud variable y punteros a arrays de longitud variable. Los tipos modificados de forma variable deben declararse en el ámbito del bloque o en el ámbito del prototipo de la función.

Las arrays de longitud variable son una función en la que podemos asignar una array automática (en la pila) de tamaño variable. Se puede utilizar en una instrucción typedef. C admite arrays de tamaño variable del estándar C99. Por ejemplo, el siguiente programa se compila y funciona bien en C.

void fun(int n)
{
 int arr[n];
 // ......
}  
int main()
{
  fun(6);
}

NOTA: En los estándares C99 o C11 , existe una función llamada miembros de array flexible , que funciona igual que la anterior. 

Pero el estándar C++ (hasta C++11) no admite arrays de tamaño variable. El estándar C++11 menciona el tamaño de la array como una expresión constante. Entonces, el programa anterior puede no ser un programa C++ válido. El programa puede funcionar en el compilador GCC, porque el compilador GCC proporciona una extensión para admitirlos.
Como nota al margen, el último C++ 14 menciona el tamaño de la array como una expresión simple (no una expresión constante). 
Implementación

C

// C program for variable length members in structures in
// GCC before C99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Structure of type student
struct student {
    int stud_id;
    int name_len;
    int struct_size;
    char stud_name[0];
    // variable length array must be
    // last.
};
 
// Memory allocation and initialisation of structure
struct student* createStudent(struct student* s, int id,
                              char a[])
{
    s = malloc(sizeof(*s) + sizeof(char) * strlen(a));
 
    s->stud_id = id;
    s->name_len = strlen(a);
    strcpy(s->stud_name, a);
 
    s->struct_size
        = (sizeof(*s)
           + sizeof(char) * strlen(s->stud_name));
 
    return s;
}
 
// Print student details
void printStudent(struct student* s)
{
    printf("Student_id : %d\n"
           "Stud_Name : %s\n"
           "Name_Length: %d\n"
           "Allocated_Struct_size: %d\n\n",
           s->stud_id, s->stud_name, s->name_len,
           s->struct_size);
 
    // Value of Allocated_Struct_size here is in bytes.
}
 
// Driver Code
int main()
{
    struct student *s1, *s2;
 
    s1 = createStudent(s1, 523, "Sanjayulsha");
    s2 = createStudent(s2, 535, "Cherry");
 
    printStudent(s1);
    printStudent(s2);
 
    // size in bytes
    printf("Size of Struct student: %lu\n",
           sizeof(struct student));
    // size in bytes
    printf("Size of Struct pointer: %lu", sizeof(s1));
 
    return 0;
}
Producción

Student_id : 523
Stud_Name : Sanjayulsha
Name_Length: 11
Allocated_Struct_size: 23

Student_id : 535
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 18

Size of Struct student: 12
Size of Struct pointer: 8

Este artículo es una contribución de Abhay Rathi y Sanjay Kanna . Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *