I am trying to create a array of structure elements and reallocate if I need new elements. The array has to be a pointer because I want to return it from the function.
I have the following code:
#include <stdio.h>
#include <stdlib.h>
struct rle_element {
int length;
char character;
};
void get_rle() {
struct rle_element *rle = malloc(sizeof(struct rle_element*));
struct rle_element **rle_pointer = &rle;
rle = realloc(rle, sizeof(rle) + sizeof(struct rle_element*));
(*rle_pointer)->length = 10;
printf("%d\n", (*rle_pointer)->length);
rle_pointer = &rle+1;
(*rle_pointer)->length = 20;
printf("%d\n", (*rle_pointer)->length);
}
int main() {
get_rle();
return EXIT_SUCCESS;
}
But this code isn't really working. I think the reallocate is not right.
Now I have the following code which works fine. But I can also use rle[2] or rle[3] without allocate. I think my programm only allocate space for two items.
#include <stdio.h>
#include <stdlib.h>
struct rle_element {
int length;
char character;
};
void get_rle() {
struct rle_element *rle = malloc(sizeof(struct rle_element));
struct rle_element **rle_pointer = &rle;
rle = realloc(rle, sizeof(rle) + sizeof(struct rle_element));
rle[0].length = 10;
printf("%d\n", rle[0].length);
rle[1].length = 20;
printf("%d\n", rle[1].length);
}
int main() {
get_rle();
return EXIT_SUCCESS;
}
sizeof(struct rle_element*)is the size of a pointer (probably either 4 or 8 bytes depending on your hardware). You wantsizeof(struct rle_element).