0

I can't for the life of me figure out how to solve this in c.

I have the following structs:

typedef struct
{
    uint8_t         index = 0;
    DLPageItem_t    *pageItems = NULL;
    uint8_t         pageItemCount = 0;
    uint8_t         selectedItemIndex = 0;
} DLPage_t;

typedef struct
{
    uint8_t         index = 0;
    void            *valuePtr = NULL;
    uint16_t        tmpValue = 0;
    DLItemType_t    type = DLITEMTYPE::NOTYPE;
    uint8_t         row = 0;
    uint8_t         col = 0;
    uint8_t         targetPageId = 0;
    DLItemAction_t  action = DLITEMACTION::EDIT;
    bool            selectable = false;
    bool            editing = false;
} DLPageItem_t;

And I want to have a dynamic array of DLPage_t (with realloc) and then be able to anytime add DLPageItem_t to any of the already created DLPage_t array members.

So I tried to have a

DLPage_t *_pages = NULL;

and do

this->_pageCount++;    
this->_pages = (DLPage_t*)realloc(this->_pages, this->_pageCount * sizeof(DLPage_t));

Then I'm accessing the "pages" and setting the values like this:

this->_pages[this->_pageCount - 1].index = this->_pageCount - 1;

The function which adds DLPageItem_t structs to a DLPage_t struct member, I do it like this:

this->_pages[pageId].pageItemCount++;
    this->_pages[pageId].pageItems = (DLPageItem_t*)realloc(this->_pages[pageId].pageItems, this->_pages[pageId].pageItemCount * sizeof(DLPageItem_t));

I have some very funny business going on so I guess I'm doing something wrong and accessing/overwriting memory where I shouldn't.

Can someone please verify whether what I'm doing is correct? I tried to apply/adapt this to my issue but I just can't figure it out: https://stackoverflow.com/a/15397992

Thanks!

9
  • 2
    c/c++. -- There is no such language. Since you tagged this as C++, use std::vector and leave realloc alone. Commented Oct 28, 2021 at 0:27
  • c++ because i use classes. i am on avr with arduino framework (there you have it) and don't have vectors available. Commented Oct 28, 2021 at 0:35
  • Post your code compile-able here. Thanks! Commented Oct 28, 2021 at 0:37
  • If you can't use std::vector then I suggest writing your own vector class to isolate the array logic, and then use that class wherever you need a dynamic array. Commented Oct 28, 2021 at 0:40
  • realloc doesn't have to return a valid pointer are you checking for those cases? Commented Oct 28, 2021 at 0:45

0

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.