Declaring a variable-length array of fixed-length strings

I need an array of strings. The length of the line is known at compile time, and it is important that each line takes up so much space. On the other hand, the number of lines is known only at runtime. What is the syntax for this?

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

+4
source share
3 answers

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

 typedef char fixed_string[STRLENGTH]; fixed_string *data; 
+10
source
 char* data[STRLENGTH] 

declares an array of STRLENTGH pointers to char . To declare a pointer to an array from STRLENGTH char s, use

 char (*data)[STRLENGTH] 
+5
source
 char (*data)[LEN]; // where LEN is known at compile time ... data = malloc(sizeof *data * rows); // where rows is determined at run time ... strcpy(data[i], some_name); ... printf("name = %s\n", data[i]); ... free(data); 

Note that data is a pointer type, not an array type ( data is a pointer to an array of the LEN char element). A malloc call will dynamically allocate enough memory to hold rows of LEN length arrays. Each data[i] will be of type char [LEN] .

+4
source

Source: https://habr.com/ru/post/1413614/


All Articles