How do I get each row of my matrix to store a substring?

Asked

Viewed 48 times

-2

Suppose the user typed: I am very beautiful

Each row of the Matrix would store a substring thus:

  • I
  • am
  • much
  • beautiful
  • One possibility is you define an array of pointers to char and dynamically allocate memory to store each string and point for each element of the array. Search for the Strtok function (https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtok.html).

1 answer

1

  • 1) Set the amount of words you want to read to the matrix.

  • 2) Create a char** and use malloc by passing as the parameter the size of intptr_t * the number of words you want to read

  • 3) Create a char[N] where N is the maximum number of letters in a single word

  • 4) Create a loop for reading the values in each iteration (Number of words you want to read), store the word in the step variable 3

  • 5) Perform a malloc on the step 2 variable for each word by indexing it into the loop iteration variable. In this malloc you will use the size of the word read (strlen) + 1 (NUL Byte)

  • 6) Use the strcpy function to pass the read buffer (step 3 variable) to the matrix (step 2 variable)

Don’t forget after using free() to free up memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.