this post was submitted on 14 Nov 2023
12 points (92.9% liked)

C Programming Language

998 readers
1 users here now

Welcome to the C community!

C is quirky, flawed, and an enormous success.
... When I read commentary about suggestions for where C should go, I often think back and give thanks that it wasn't developed under the advice of a worldwide crowd.
... The only way to learn a new programming language is by writing programs in it.

ยฉ Dennis Ritchie

๐ŸŒ https://en.cppreference.com/w/c

founded 1 year ago
MODERATORS
 

I'm trying to create a dynamic array which can be modified using the functions Array_Push(array, val) & Array_Del(array, index). Now the current way I have this I need a variable to keep track of the size of it. My implementation of this concept is to store the data/size in a struct like so:
โ€ƒstruct Array {
โ€ƒโ€ƒvoid **data;
โ€ƒโ€ƒint size;
โ€ƒ}
However in order to read the actual array you have to type array.data[i] which I think is a little bit redundant. My solution to this was attempting to store the size of the array in a different index. I didn't want to store it inside [0] as that would create a lot of confusion, so I wanted to try storing it inside of [-1]. An obvious problem with this is that [-1] is outside the array. What I did instead was create an array via void **array = malloc(sizeof(void*) * 2) (the * 2 is so when you push with realloc() it doesn't free empty memory,) then setting the size via array[0] = (void *)0. After that I increment the pointer to it via array += 1. However when I try to free it free(array - 1), I end up freeing non malloc()ed. I think this is just an issue with my understanding of pointers, so I wanted to ask where my logic is going wrong, along with if anybody actually knows how to do what I'm trying to do (in the title).

top 2 comments
sorted by: hot top controversial new old
[โ€“] [email protected] 4 points 1 year ago* (last edited 1 year ago)

You could use a sentinel value to terminate your array, like null terminated strings... But then you get that whole set of problems. I don't understand why you're allocating 2x the space... But maybe I just don't know what that realloc stuff means. You should be able to shift your pointer arbitrarily and free should work as long as the address is correct. I think it's a good idea to try storing the length in "-1", maybe there's just a bug in your implementation?

[โ€“] vcmj 0 points 1 year ago

Maybe use a flexible struct? You can have an indeterminate array at the end (https://www.geeksforgeeks.org/flexible-array-members-structure-c/) I'd rather just use the variable in the struct though. The packing isn't guaranteed to be right next to each other