Reputation: 3235
How to create an array of strings when there isn't a fixed length of items or characters. I'm new to pointers and c in general and I couldn't understand the other solutions posted on here so my solution is posted below. Hopefully it helps someone else out.
Upvotes: 3
Views: 10468
Reputation: 2597
Yours is close, but you are allocating the main array too many times.
char **dirs = NULL;
int count = 0;
dirs = malloc(sizeof(char*) * (argc - 1));
if(dirs==NULL){
fprintf(stderr,"Char* malloc unsuccessful");
exit(EXIT_FAILURE);
}
for(int i=1; i<argc; i++)
{
int stringSize = strlen(argv[i])+1;
dirs[count] = malloc(stringSize);
if(dirs[count]==NULL){
fprintf(stderr,"Char malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(dirs[count], argv[i]);
count++;
}
Upvotes: 1
Reputation: 25705
char **twod_array = NULL;
void allocate_2darray(char ***source, int number_of_slots, int length_of_each_slot)
{
int i = 0;
source = malloc(sizeof(char *) * number_of_slots);
if(source == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
for(i = 0; i < no_of_slots; i++){
source[i] = malloc(sizeof(char) * length_of_each_slot);
if(source[i] == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
}
}
// sample program
int main(void) {
allocate_2darray(&twod_array, 10, 250); /*allocate 10 arrays of 250 characters each*/
return 0;
}
Upvotes: 2
Reputation: 3235
Simply makes an array from the argv items bar the first item.
char **dirs = NULL;
int count = 0;
for(int i=1; i<argc; i++)
{
int arraySize = (count+1)*sizeof(char*);
dirs = realloc(dirs,arraySize);
if(dirs==NULL){
fprintf(stderr,"Realloc unsuccessful");
exit(EXIT_FAILURE);
}
int stringSize = strlen(argv[i])+1;
dirs[count] = malloc(stringSize);
if(dirs[count]==NULL){
fprintf(stderr,"Malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(dirs[count], argv[i]);
count++;
}
Upvotes: 1