Initialization of Array inside a Structure in C
I'm trying to开发者_StackOverflow allow a variable length array inside a struct in a C program. Something like this:
struct result{
int column;
int row;
const char* a[var][var];
};
how do i do this?
even the following definition would do:
struct result{
int column;
int row;
const char* a[row][column];
};
plese do help...
You can't have variable size arrays in C structs.
You can have pointers to arrays which can be variable size (you need to handle the allocation of the space separately), but you are declaring arrays of pointers instead
If you want an array of pointers, try
const char (*a)[][];
(you'll need to manage the array as an array of pointers to arrays if you want both dimensions to be variable)
Just use pointers instead. You'll have to do dynamic memory allocation. Don't forget to free() the memory allocated for your array :)
P.S.: If you need a 2-dimensional array, use a pointer-to-pointer (that is, allocate memory for an array of pointers)
For single-dimension arrays you can do something like this:
struct TEST {
...
int size;
char string[];
}
where the size field indicates how many characters there are in the string array. The array has to be the last member of the struct, and you have to allocate the struct's memory dynamically. The allocated size should be sizeof(struct TEST) + size * sizeof(char)
in this case.
You cannot have more than one variable size array in the struct. Multi-dimension variable-size arrays are trickier. It cannot be done unless only one dimension size is unknown, specifically that of the first dimension.
struct TEST {
...
int size;
char string[][100];
}
EDIT:
As other posters mentioned, you can have pointers to one or more arrays, at the cost of having to manage their memory areas separately from the struct.
EDIT 2:
This is part of at least the ISO C99 standard. Shamelessly copying from paragraph 6.7.2.1, sub-paragraph 16:
16 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. With two exceptions, the flexible array member is ignored. First, the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length.106)...
Use dynamic allocation with the malloc function.
In your case you should do something like:
#include <stdlib.h> /* header file for the malloc function */
void allocateResult(struct result* res, int row, int column) {
res->a = (const char*) malloc(row * column * sizeof(char));
}
Please note that sizeof(char)
equals to 1 (almost all the time), but for other types you'd have to do it this way.
This solution implies to free allocated memory before the program ends. You'll have to pass the pointer in your struct to free:
void freeResult(struct result* res) {
free(res->a);
}
精彩评论