I am currently trying to learn C and I have come to a problem that I’ve been unable to solve.
Consider:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ELEMENTS 5 void make(char **array, int *array_size) { int i; char *t = 'Hello, World!'; array = malloc(ELEMENTS * sizeof(char *)); for (i = 0; i < ELEMENTS; ++i) { array[i] = malloc(strlen(t) + 1 * sizeof(char)); array[i] = strdup(t); } } int main(int argc, char **argv) { char **array; int size; int i; make(array, &size); for (i = 0; i < size; ++i) { printf('%s\n', array[i]); } return 0; }
I have no idea why the above fails to read back the contents of the array after creating it. I have literally spent an hour trying to understand why it fails but have come up empty handed. No doubt it’s something trivial.
Cheers,
Here is the working code:
As the other have posted – there was unused size, and strdup allocates memory by itself, and it is nice to free the memory afterwards…