C saving strings to 2d array

883 views Asked by At

The idea is to read strings from standard input until EOF is reached (in this format "string - string"). Then, break the string into two strings and and save them to a 2d array. The array is dynamically allocated with initially 2 rows and 20 columns, but I would like to add 2 additional rows every time I want to add next strings to it (the function expandmat()). Here's my code:

char ** alloc(int rows, int collums) {
   char ** mat;
   int i;
   mat = malloc(sizeof (char *) * rows);
   for (i = 0; i < rows; i++) {
      mat[i] = malloc(sizeof (char) * collums);
   }
   return mat;
}

char ** addtoarray(char ** mat, char * string1, char * string2, int position) {

   sscanf(string1, "%s", mat[positon]);
   sscanf(string2, "%s", mat[positon+1]);
   return mat;
}

char ** getinput(char * longstring, char * string1, char * string2) {

   int position = 0, n = 2, max = 30;
   char ** mat;
   mat = alloc(n, max);
   while (fgets(longstring, max, stdin)) {
        sscanf(longstring, "%s - %s", string1, string2);
        addtoarray(mat, string1, string2, positon);
        n += 2;
        position += 2;
        mat = expandmat(mat, n);
   }

   return mat;
}

Also, if there is something in this code that doesnt make any sense, could you please tell me how to fix it?

I know this seems like a trivial task but it has been driving me crazy.

Thanks for your help.

2

There are 2 answers

2
Foo Bah On

Check out the realloc C function to resize mat.

expandmat should realloc mat so that you can add two more rows (it should return the matrix as well, because realloc will copy memory to a new location if necessary)

0
yankee On

Wow... The third time that a question like this comes up for today :-).

Please check if my answer here helps you: Array of C structs