0

Hello everyone I got the following struct

struct Test
{
    unsigned char* c_string;
    unsigned int value;
};

I created a function that creates a new instance of this struct and initialize the attributes with random values like this

struct Test* createNewTest(){
struct Test *NewInstance = (Test * )malloc( sizeof(Test) );
NewInstance->value = rand();

Now I have to create a function that creates n completely initialized instances of my struct.

struct Test** createNewArray(unsigned int n){
};

Can anyone help me to do this? I dont really now how to start here

Jimmy589
  • 13
  • 3
  • Welcome to Stack Overflow! [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Apr 05 '17 at 12:36
  • 2
    `sizeof(Test)` --> `sizeof(struct Test)` – Sourav Ghosh Apr 05 '17 at 12:37
  • Not sure what you are trying to achieve by assigning the pointer c_string to a random number, doesn't look to smart. If you want to use sizeof(Test), prefix your structure with typedef and append the name to the structure. – SPlatten Apr 05 '17 at 12:37
  • `NewInstance->c_string = rand();` is your compiler does not complain, you actually have a problem in your environment. – Sourav Ghosh Apr 05 '17 at 12:37
  • Sorry I copied the wrong version there should not be a New Instance ->c_string = rand(); – Jimmy589 Apr 05 '17 at 12:40
  • Break the problem down into parts rather than viewing it as one large whole - like start of, by thinking how you'd allocate the space for your array for example. – Chris Turner Apr 05 '17 at 12:46

2 Answers2

1

It's fairly straightforward. First, you'll need to allocate enough storage for n pointers to struct Test:

struct Test **array = malloc(n * sizeof *array);
if (!array) return array;

And then assign each pointer, using the function you have:

for (size_t i = 0;  i < n;  ++i)
    array[i] = createNewTest();

Wrapping it all up, you get

struct Test **createNewArray(size_t n)
{
    struct Test **array = malloc(n * sizeof *array);
    if (!array) return array;

    for (size_t i = 0;  i < n;  ++i)
        array[i] = createNewTest();

    return array;
}

Don't forget to write a matching free() function!

Also, consider whether you really want an array of pointers to Test - you may be better off with an array of Test objects instead.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
0

I'm going to try to explain this without giving you the answer to your assignment verbatim ...

First, you need to allocate n times as much memory. malloc can allocate any amount, so you just need to calculate the number.

Second, you need to do the same initialization, but for each entry in the array. You'll need a loop for that.

Hint: in C, a pointer to a single instance and a pointer to a dynamic array are indistinguishable. ptr->value is the same as ptr[0].value, and ptr[1].value is the next element in the array.

ams
  • 24,923
  • 4
  • 54
  • 75