#unable to allocate dynamic memory to a field inside a struct

20 messages · Page 1 of 1 (latest)

raven mesa
#

Hey,
for some reason this code

{
    int year;
    int n_tracks;
    char *category;
     category = (char *) malloc (sizeof(char) * 50);

};

throws me this error:
"expected specifier-qualifier-list before category" and cant understand why it does it.
i've tried looking online but most of the issue was'nt related to dynamic memory.

coarse siloBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

obsidian ingot
#

You can't assign values during a struct declaration

#

You'd have the declaration as:

struct records_DB
{
    int year;
    int n_tracks;
    char *category;
};
```and then initialize an instance like this:
```c
struct records_DB a = (struct records_DB) { .years=some_value; .n_tracks=some_other_value; .category=malloc(50) };
```but if you're always using a fixed size of `50` for the string's size then you can also just declare it as:
```c
struct records_DB
{
    int year;
    int n_tracks;
    char category[50];
};
```completely erasing the `malloc` call and thereby the need to `free` the string again.
raven mesa
#

@obsidian ingot There's a requirement for dynamic allocation only, which is why I did it like that, also I'm using array of structs, wouldn't that be a problem to do it the way you did it

#

I think I forgot to mention that which might be my bad

obsidian ingot
#

I think when they want you to include dynamic allocation they don't mean for you to malloc memory for a fixed size string, but rather to dynamically allocate memory for new struct records_DB

raven mesa
#

even if I do so I still need to allocate memory to category no?

obsidian ingot
#

If you do char category[50] then no

raven mesa
#

Yeah but I'm not allowed, im only allowed to use dynamic allocation - no fixed size

obsidian ingot
#

Then all you need to do is set it to some value, like f.e. .category={ 0 } for an empty string or .category="abc" if you want to set it to "abc"

raven mesa
#

stupid I know

obsidian ingot
raven mesa
#

It's in hebrew and pretty long

obsidian ingot
#

ah okay

#

well, yeah. I'd say to make category be the array like I did and have a struct records_db *records which you dynamically grow/shrink depending on how many records there are

raven mesa
#

struct records_DB a = (struct records_DB) { .years=some_value; .n_tracks=some_other_value; .category=malloc(50) }; like this right?

obsidian ingot
#

Yeah, but that works only if you have a char pointer there which again is not what I'd suggest.
If you do it with char category[50] then you can do:

struct records_DB a = (struct records_DB) { some_value; some_other_value; "some_category" };
raven mesa
#

okay, thanks alot

#

@obsidian ingot