I am trying to create a program that populates a fixed-size argument array using the arguments passed through the terminal. My first step is trying to create and populate the array of default argument strings, which I have succeeded in doing. However, I am now trying to use malloc()
to allocate space for this array, and cannot get it to compile. I've tried everything I can think of regarding the proper syntax. I've tried doing more research into malloc()
and how to use it for two dimensional arrays, but I haven't found any information that helps me. I'm stuck and not sure what to do next. Here is the code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_NUM_OF_ARGS 5
#define MAX_ARG_SIZE 256
int main(int argc, char **argv) {
printf("%s%d\n", "Length: ", argc); //for debug purposes
// Make sure we don't have more than five arguments
if(argc > MAX_NUM_OF_ARGS) {
printf("%s", "Too many arguments. Must enter fewer than 4.");
}
// Populate the array
else{
char defaultArgs[] = "defaultArgs"; //create default argument array
//allocate memory for default array
char argumentArray[MAX_NUM_OF_ARGS][MAX_ARG_SIZE] =
(char *)malloc(MAX_NUM_OF_ARGS * MAX_ARG_SIZE * sizeof(char));
//populate array with default arguments
for (int i = 0; i < MAX_NUM_OF_ARGS; i++) {
strcpy(argumentArray[i], defaultArgs);
printf("%s\n", argumentArray[i]);
}
free(argumentArray);
return 0;
}
}
When I try to compile I get an invalid initializer error at the (char*
) cast for malloc()
. I've tried casting it to (char**
) and (char
) and also changing the sizeof(char)
to sizeof(char*)
and sizeof(char**)
.
I am not really sure what I am doing wrong at this point and I am at a loss as far as what to even try next.