I created a previous thread of re-sizing dynamic arrays.

I got the answers to that question and I could re-size the dynamic arrays but when I tried to apply similar steps to creating a dynamic array of struct, my program compiles but crashes when i try to run it.

--------------outside main function----------------

typedef struct{
 sprite _sprite;
 float x_pos;
 float y_pos;
 vector vec;

------------in main function--------------

int initial_num_bricks = 1;
 sprites *sprites_pointer = NULL;
 sprites_pointer = (sprites *)malloc(initial_num_bricks * (sizeof(sprites)));
populate_bricks(bitmap_names, sprites_pointer, initial_num_bricks);

-------------------populate_bricks procedure--------------

void populate_bricks(const char **_sprite_bmap_names, sprites *sprites_pointer, int &sprites_size){
 //bmap = randomly_select_sprite_bitmap(_sprite_bmap_names, BRICKS_SIZE);

int sprites_counter = 0;
 sprites_pointer[sprites_counter]._sprite = create_sprite(bitmap_named("red_brick"));
 initi_sprite_settings(sprites_pointer[sprites_counter]._sprite, random_x_pos, y_pos, vector_to(0, 0));
 sprites *temp_ = (sprites*) realloc (sprites_pointer, (sprites_size) * sizeof(sprites));
 if(temp_ != NULL){
 sprites_pointer = temp_;

Can anyone see what I am doing wrong?

5 Years
Discussion Span
Last Post by Narue

Can anyone see what I am doing wrong?

Yes, and I can illustrate the issue in a test program for you:

#include <stdio.h>

void reset(int value)
    value = 123;

int main(void)
    int x = 0;
    printf("%d\n", x);
    return 0;

value is a copy of the original object, not a reference to it. Thus when you modify value , the original object does not change, and the output of this program will be 0 instead of 123. The thing is, if you add a level of indirection such that x becomes a pointer, that changes nothing, and if you look at your definition of populate_bricks(), sprite_pointer is being modified yet it's a copy of the original object.

Since you're clearly compiling as C++ rather than C, you can make that parameter a reference and nothing else needs to change:

void populate_bricks(const char **_sprite_bmap_names, sprites*& sprites_pointer, int &sprites_size)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.