Hello,
I read the example on "Passing multi-dimensional arrays in C" on this site.
It is a great example using char arrays, and I learned a lot from it. I would like to do the same thing by creating a function to handle a dynamically allocated one-dimensional integer array, and after that, create another function for handling a multi-dimensional integer array. I know how to do it as a return value to a function. But in this application I need to do it on the argument list to the function.
Just like in the example I mentioned above, I would like to pass a pointer to an integer array to a function, along with the number of elements "num" (or "row" and "col" for a 2D array function, etc.). I got a reworked version of the other example here, but I cannot get this to work, try as I might (lines of code that are new, or modified, from that example, are marked). Does anyone know how to solve this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
void make(char **array, int **arrayInt, int *array_size) {
int i;
char *t = "Hello, World!";
int s = 10; // new
array = malloc(ELEMENTS * sizeof(char *));
*arrayInt = malloc(ELEMENTS * sizeof(int *)); // new
for (i = 0; i < ELEMENTS; ++i) {
array[i] = malloc(strlen(t) + 1 * sizeof(char));
array[i] = StrDup(t);
arrayInt[i] = malloc( sizeof(int)); // new
*arrayInt[i] = i * s; // new
}
}
int main(int argc, char **argv) {
char **array;
int *arrayInt1D; // new
int size;
int i;
make(array, &arrayInt1D, &size); // mod
for (i = 0; i < size; ++i) {
printf("%s and %d\n", array[i], arrayInt1D[i]); // mod
}
return 0;
}