1

Given a struct Element:

typedef struct {
    char someString[9]
    int value;
} Element

and an array elementList:

Element elementList[5];

is there an easy way to dynamically add an Element to each index of the list? I have tried creating a function add_element that takes in the list and modifies it there but I'd prefer something equivalent to Java's elementList[i] = new Element.

1
  • each part of that array is already an element. You do not need to do "new", memory has already been allocated and elementList[1] can be addressed directly (although it may contain rubbish unless you initialize it...) Commented Mar 4, 2016 at 14:56

2 Answers 2

4

There's no need, that array consists of structure instances.

You can do e.g.:

strcpy(elementList[0].someString, "foo");
elementList[0].value = 4711;

This is not possible in Java, where everything is a reference, but in C you can do this. If you want a bunch of NULL-able references, in C you use pointers:

Element *elementList[5]; /* An array of 5 pointers to type Element. */

Then you have to use e.g. heap allocations to make sure there is memory before accessing the Element:

elementList[0] = malloc(sizeof *elementList[0]); /* This might fail! */
elementList[0]->value = 17;
Sign up to request clarification or add additional context in comments.

Comments

1

As declared, you've created a 5-element array of Element instances; there's no need to allocate new Element objects. You can go ahead and read/assign each member of each element:

element[i].value = some_value();
strcpy( element[i].someString, some_string() );

If you want to emulate the Java method, you'd do something like the following:

Element *elementList[5]; // create elementList as an array of *pointers* to Element
...
elementList[i] = malloc( sizeof *elementList[i] ); // dynamically allocate each element

Note that in this case, you'd use the -> operator instead of the . operator to access each Element member, since each elementList[i] is a pointer to Element, not an Element instance:

elementList[i]->value = some_value();
strcpy( elementList[i]->someString, some_string() );

In either case, the array size is fixed; you cannot grow or shrink the number of elements in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.