0

For example, given input string "this is a test" I want to create an array of strings with 4 elements: "this", "is", "a", and "test". I also want to be able to change these strings later.

Below is the code I have tried. This seems to put all the characters into the first string in the array.

    char string[] = "this is a test string"; //sample input string
    size_t sizee = sizeof(string) - 1; //size of sample input string
    char arrayOfStrings[sizee][sizee]; //the array of strings

    int m = 0; //[m][n]
    int n = 0; //[m][n]
    for(int i = 0; i<sizee; i++){
            if(string[i] != " "){
            arrayOfStrings[m][n] = string[i];
            n++; //
            }

            else{
            m++; //if space char, move to next string in the array
            n = 0;
            }
    }
Wilfredo
  • 137
  • 1
  • 9
  • What is the `-1` for? Why do you use `sizeof` and not `strlen`? Why does the coded test string not match the question? – Weather Vane Jul 18 '17 at 19:50
  • 7
    `if(string[i] != " ")` will generate a compiler complaint. Enable full compiler warnings and do not ignore them. – Weather Vane Jul 18 '17 at 19:51
  • You can also simply process your string until the *nul-terminating* character is reached, e.g. `for(int i = 0; string[i]; i++)` or `char *p = string; while (*p) { /*handle char*/; p++; }` – David C. Rankin Jul 18 '17 at 20:00
  • 1
    When learning C or C++, enable all warnings with `-Wall -Werror` for clang or gcc, and `/W4 /WX` for msvc. – Ben Jul 18 '17 at 20:01
  • 1
    `size_t sizee = sizeof(string) - 1; char arrayOfStrings[sizee][sizee];` is one too small. Consider `char string[] = "123";` Suggest `char arrayOfStrings[sizeof string/2 + 1][sizeof string];` – chux - Reinstate Monica Jul 18 '17 at 20:02
  • [sample code](http://ideone.com/NLSxo5) – BLUEPIXY Jul 18 '17 at 21:55

0 Answers0