You only allocate memory for the structure itself. This includes a pointer to char, which is only 4 bytes on a 32-bit system, since it is part of the structure. It does NOT include memory for an unknown string length, so if you want to have a string, you must also manually allocate memory for it. If you just copy the string, you can use strdup() , which selects and copies the string. You still have to free your memory.
mystruct* structptr = malloc(sizeof(mystruct)); structptr->word = malloc(mystringlength+1); .... free(structptr->word); free(structptr);
If you do not want to allocate memory for the string itself, your only choice is to declare a fixed-length array in your structure. Then it will be part of the structure, and sizeof(mystruct) will include it. If applicable or not, depends on your design.
Devolus
source share