I want to initialize a structure with an array of string without doing dynamic allocation. Is it possible? I had thought of something like this but it doesn't work:
struct st_request {
int GRID;
char NAME[15];
char (*PARAM)[15];
};
typedef struct st_request request;
request myrequest = {
.GRID=1,
.NAME="GLOB",
.PARAM={"RR1","RR3"}
}
An idea? Thanks for your solutions.
The line
char (*PARAM)[15];
declares a single pointer PARAM
which points to an array of type char[15]
, i.e. to an array of 15 elements, in which each element has the type char
.
You probably want to write
char *PARAM[15];
which declares an array of 15 pointers, in which each pointer has the type char*
. In contrast to the pointer mentioned earlier, which points to an entire array, these 15 pointers only point to a single character.
In C, when handling strings, it is normal to use pointers to the first character of a null-terminated character sequence. Pointers to entire arrays are normally only used in the context of multi-dimensional arrays, because the size information of the referenced object is needed to calculate the offset in a multi-dimensional array.
Note that it is not normal to write the names of variables in upper-case. This is normally reserved for constants.
Also, there is a ;
missing in the last line of your code.