Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic array of strings in C using malloc

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.

like image 250
Cadell Christo Avatar asked May 29 '26 09:05

Cadell Christo


2 Answers

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;
}
like image 50
Aniket Inge Avatar answered Jun 01 '26 00:06

Aniket Inge


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++;
}
like image 44
Cadell Christo Avatar answered May 31 '26 23:05

Cadell Christo