October 26, 2024
Chicago 12, Melborne City, USA
C#

how to increment a void pointer in C by specifying the amount of bytes


I have a "list" struct.

typedef struct list
{
    int count;                  // how many elements are in the list
    void *start;                // our pointer to the start of the array
    unsigned char size;         // how many bytes each element will hold
}
list;

And I want to get a void pointer to a specific element in the struct. I’m not sure of the syntax though, it keeps giving me segmentation faults.

static void* dev_list_get(list *list, int index)
{
    return (void *)((char *) list->start) + (index * list->size);
}

If we cast the void pointer to a char pointer and add 1 to it then that increases the pointer to the next memory slot in line so we need to increase it by the # of bytes right?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video