What am I misunderstood on char **?

advertisements

I'm working on some homework for a computer science class and the last part of a rather tedious assignment is to write a function that can reverse sentences. The function prototype provided by the professor looks like this:

int reverseSentence(char** sentence, char **
                newsentence, int maxWords)

...where sentence is the original sentence, newsentence is where we're supposed to dump the reversed sentence, and maxWords is the number of words in the original sentence. I wrote my function like this...

int reverseSentence(char** sentence, char **
                newsentance, int maxWords)
{

    int i = maxWords;
    int x = 0;
    while(i > 0){
        newsentance[x] = sentence[i];
        x++;
        i--;
    }

    return maxWords;
}

However, the loop seems to be going on forever. Also, I seem to have a misunderstanding about how to make use of char**. I thought it was just an array of strings, like char[words][characters]. But I'm getting warnings about passing in an array of words to the function in that form. I'm not asking for anyone to do the homework for me, just to clear up what I'm missing about how to use char**.

Any help is appreciated. Thank you.

P.S - This is how I tried testing my code:

char sentence[3][4] = {"Hi\n", "my\n", "fri\n"};
char newsentence[3][4];
reverseSentence(sentence, newsentence, 3);


As indicated in your comment, the code

char sentence[3][4] = {"Hi\n", "my\n", "fri\n"};

is valid but isn't compatible with a char **. Instead, it should be:

char *sentence[3] = {"Hi\n", "my\n", "fri\n"};

The first one is laid out in memory like this, characters packed into one block, three groups of four characters each:

+---+---+---+---+---+---+---+---+---+---+---+---+
| H | i | \n| \0| m | y | \n| \0| f | r | i | \n|
+---+---+---+---+---+---+---+---+---+---+---+---+

Note that the final entry does not have a trailing NUL (\0), because there is no room in the 4 characters available in the array.

The second declaration (what you want) is an array of three pointers to NUL-terminated strings:

+---------------+---------------+---------------+
|    char *     |    char *     |    char *     |
+---------------+---------------+---------------+
       |               |               |
       |               |               |    +---+---+---+---+---+
       |               |               +--> | f | r | i | \n| \0|
       |               |                    +---+---+---+---+---+
       |               |    +---+---+---+---+
       |               +--> | m | y | \n| \0|
       |                    +---+---+---+---+
       |    +---+---+---+---+
       +--> | H | i | \n| \0|
            +---+---+---+---+