Search code examples
cstructchardynamic-memory-allocationvariable-length-array

Char with a variable length


Is it possible to define a char with a variable length?

I have a char "name" (member of a struct named "person") with a length of 25 but I want it to be a variable length between the values 1 and 25, because I want to generate random strings of that char with different sizes and not always with the same length (25). One of the parameters of the method is sizeof(n.name).

Note: n is a struct (struct person n).

The struct "person" is defined this way:

    struct person{
       int c; 
       char name[25];
    };

Anyone?


Solution

  • struct person{
       int c; 
       char name[]; /* Variable length array */
    };
    

    I think this should serve your purpose.

    Else you can have dynamic memory allocation using

    char *name;
    

    name is a pointer and memory should be allocated and it can be done using malloc()