2

I recently learnt structures in c and have known much about it. So if i have a structure like this:

struct test{
  int value1;
  int value2;
};

Can I add int value3 to the structure without having to edit the initial structure's declaration? [or re-declare the struct if possible]

I searched across many search engines and StackOverflow.com itself but I didn't find any questions like this nor answers nor any restrictions.

If there is any kind of way doing this in PURE C, it would be helpful to know

Zuri Bret
  • 21
  • 3
  • If the members are all the same type, you can use a dynamically allocated array instead of `struct` and reallocate it to add an element. – Weather Vane May 22 '22 at 09:20
  • `Can I add int value3 to the structure without having to editing the initial structure's declaration` What is the use case ? Is this `struct test` written into some database so that adding new `value3` will cause issue for existing data ? – Achal May 22 '22 at 09:21
  • @Achal no, it is because I have a structure template and I want user's to be able to edit it without modifying my header file - [probably worthless but also is it possible?] – Zuri Bret May 22 '22 at 09:22
  • `int array[2]` is fixed (not necessarily static), but `int *array` can be dynamically allocated and indexed like an array. – Weather Vane May 22 '22 at 09:22
  • @WeatherVane and what if I have different type of elements? – Zuri Bret May 22 '22 at 09:23
  • @WeatherVane is using malloc() good? that is in heap memory. [ many persons say not to use it else i could just create a void pointer and store everything ] – Zuri Bret May 22 '22 at 09:24
  • 4
    Is this [the XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? What are you trying to solve? – Weather Vane May 22 '22 at 09:24
  • @WeatherVane no, i want to have a structure already defined [ in this case test] in a header file. also i want to make so that user's can edit the structure without having to edit the header file. I mean copy the test struct into a new struct and add new elements to the new struct – Zuri Bret May 22 '22 at 09:27
  • 3
    Still sounds like an XY problem. Who is a 'user'? – Weather Vane May 22 '22 at 09:28
  • @WeatherVane the problem: I want to make a template-like structure in let's say test.h, then i goto main.c and #include "test.h", now i want to duplicate and edit that structure in main.c without having to edit "test.h" [ the user is literally me or anyone who is using the code ] – Zuri Bret May 22 '22 at 09:31
  • 2
    The basic answer is “No”. You can define new structure types containing the old one. You could arrange to include a macro in the original structure definition that could be defined to add extra members: `struct test { int value1; int value2; OTHER_TEST_MEMBERS };` etc. But you can't modify the contents of the structure once the close brace has been parsed. – Jonathan Leffler May 22 '22 at 09:35

0 Answers0