I am currently trying to learn C and I have come to a problem that I\'ve been unable to solve.
Consider:
#include
#include
size is declared but gets no value assigned (that should happen in function make, I suppose).
Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
void make(char ***array) {
char *t = "Hello, World!";
*array = malloc(ELEMENTS * sizeof(char *));
int i;
for (i = 0; i < ELEMENTS; ++i) {
(*array)[i] = strdup(t);
}
}
int main(int argc, char **argv) {
char **array;
make(&array);
int i;
for (i = 0; i < ELEMENTS; ++i) {
printf("%s\n", array[i]);
free(array[i]);
}
free(array);
return 0;
}
As the other have posted - there was unused size, and strdup allocates memory by itself, and it is nice to free the memory afterwards...
You are passing the current value of array to make as a copy (on the stack). when you change array in make(), you're only changing the copy, not the actual variable. Try passing by reference with &, or make it a char *** and work with *array = ...
See PolyThinker's comment which is absolutely spot on.
In addition to the way you pass the array, you should check a few other issues:
You need to pass the address of "array" into the function. That is, you need char ***. This is because you need to change the value of array, by allocating memory to it.
EDIT: Just to make it more complete, in the function declaration you need to have something like
void make(char ***array, int *array_size)
Then you need to call it using
make(&array, &size);
Inside the function make, allocate memory with
*array = malloc(ELEMENTS * sizeof(char *));
And change other places accordingly.
Also, as kauppi has pointed out, strdup will allocate memory for you, so you don't need to do malloc on each string.