Following this question, I'm trying to modify the code provided in this blog post to create an append
function using dynamic memory allocation. This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
typedef struct intlist_ {
int size;
int* list;
} intlist;
void append(intlist* arr, int value){
realloc((*arr).list, sizeof((*arr).list) + sizeof(int));
(*arr).size = (*arr).size + 1;
(*arr).list[(*arr).size -1] = value;
}
int main() {
intlist arr;
arr.size = 4;
arr.list = malloc(arr.size * sizeof(int));
arr.list[0] = 0;
arr.list[1] = 5;
arr.list[2] = 3;
arr.list[3] = 64;
append(&arr, 12);
for (int ii = 0; ii < arr.size; ii++)
printf("%d, ", arr.list[ii]);
free(arr.list);
return 0;
}
However the result I get is wrong:
clang version 7.0.0-3~ubuntu0.18.04.1 (tags/RELEASE_700/final) main.c:10:3: warning: ignoring return value of function declared with 'warn_unused_result' attribute [-Wunused-result] realloc((*arr).list, sizeof((*arr).list) + sizeof(int)); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 warning generated. 0, 5, 3, 64, 0, 5, 3, 64, 12,
I'm using this online compiler for testing where you can also see the latest versions of the above code. I would appreciate if you could help me know where is my mistake and how I can solve it. Thanks for your support in advance.
P.S. You may a final version of the code here in this Gist.