Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable-length array of fixed-length strings

I need an array of strings. The length of a string is known at compile-time and it is crucial that each string takes up this much space. The number of strings on the other hand is only known at runtime. What is the syntax for this?

char* data[STRLENGTH] is incorrect syntax. char** data mostly works but then sizeof(data[0]) is wrong -- it should be equal to STRLENGTH.

like image 533
Erik Avatar asked May 21 '12 20:05

Erik


People also ask

How do you create an array with variable length?

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself: int n = 10; double* a = new double[n]; // Don't forget to delete [] a; when you're done!

How do you write a variable length string?

To create a string of variable length:Use the Array() constructor to create an array of empty elements with length N + 1. Call the join() method on the array to join the elements with the string you want to repeat. The join method returns a new string, where the array elements are separated by the specified string.

How do you declare a fixed length array in TypeScript?

Use a tuple to declare an array with fixed length in TypeScript, e.g. const arr: [string, number] = ['a', 1] . Tuple types allow us to express an array with a fixed number of elements whose types are known, but can be different.

What is a fixed length array?

A fixed array is an array for which the size or length is determined when the array is created and/or allocated. A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages.


1 Answers

@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps:

typedef char fixed_string[STRLENGTH];
fixed_string *data;
like image 128
zmbq Avatar answered Sep 21 '22 17:09

zmbq