I would like to ask if there is a limit for a struct in C.
I have:
#define MAX_DOC_LENGTH (1<<22)
And:
struct MyDocument {
DocID doc_id;
unsigned int num_res;
QueryID* query_ids;
unsigned int size;
char str[MAX_DOC_LENGTH];
};
I would like to ask if there is a limit for a struct in C.
I have:
#define MAX_DOC_LENGTH (1<<22)
And:
struct MyDocument {
DocID doc_id;
unsigned int num_res;
QueryID* query_ids;
unsigned int size;
char str[MAX_DOC_LENGTH];
};
It depends if you are creating an instance of your structure on heap
or stack
. If you define a pointer to the object and allocate on the heap
through malloc
, then it depends on the available memory of your system.
If you define an instance of the object on the stack as struct MyDocument mydoc;
, then this is bound to fail as your system will not have such a huge stack value.
It would recommended to declare str
as a pointer i.e. char *str
and allocate the memory for the same through malloc
.
The structure definition could be redefined as
struct MyDocument {
DocID doc_id;
unsigned int num_res;
QueryID* query_ids;
unsigned int size;
char *str; // Modified the declaration
};
With this change, it doesn't matter if you create the object on stack
or heap
. If you are defining a pointer
to the object, then you could allocate the object and str
as shown in the example below
struct MyDocument *myDoc; // Declare an object pointer
myDoc = malloc(sizeof(MyDocument)); // Allocate memory for the object
myDoc->str = malloc(sizeof(char) * MAX_DOC_LENGTH); // Allocates memory for str
Alternatively, you could define an object on the stack and allocate space for str
only as
struct MyDocument someDoc; // Declare an object
someDoc.str = malloc(sizeof(char) * MAX_DOC_LENGTH); // Allocates memory for str
Here your problem is associated with the size of the string str not with the number of variables declared inside the structure. There won't be any restrictions by the compiler, if any problem occurs it will be due to the memory capacity.
4MB is a probably gonna be too big for the stack. Allocate your str
on the heap
.
struct MyDocument {
DocID doc_id;
unsigned int num_res;
QueryID* query_ids;
unsigned int size;
char* str;
};
And when you allocate:
struct MyDocument doc;
doc.str = malloc(MAX_DOC_LENGTH);
SIZE_MAX
, which is the maximum value of the size_t
type, is the absolute maximum size (in C's bytes, which have CHAR_BIT
bits in them, which is >= 8) of any single object in C.