Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 80
#define MAX_WORDS 10
int get_words (char *line, char tokens[MAX_WORDS][MAX_LEN+1]);
void replace_whitespace (char *str);
int main(void)
{
int i;
char *str, "str" doesn't point anywhere useful.
tokens[MAX_WORDS][MAX_LEN+1];
printf("Enter a sentence: ");
gets(str); gets() is dangerous, due to buffer overruns -- see the FAQ, use fgets() instead. See above, "str" does not point anywhere.
get_words(str, tokens);
printf("Reversal of sentence: ");
for (i = strlen(str); i > 0; i--)
printf("%s ", str[i]);
return 0;
}
/* store the words from string line in the array
tokens, one word per entry. */
int get_words (char *line, char tokens[MAX_WORDS][MAX_LEN+1])
{
int i, char_count = 0;
char *p = line;
int len;
replace_whitespace(p); This is incorrect logic, how do you know where the last whitespace character was replaced?
len = strlen(p); This will give you the length of the first part (upto the first whitespace character).
while (*p == '\0' && *p < len)
{
p++;
char_count++;
}
while (*p != '\0')
{
strcpy(tokens[i], p);
p += strlen(p);
while(*p == '\0')
p++;
i++;
}
}
/* replaces every whitespace character in str with the null
character; uses the function isspace(char c) from ctype.h */
void replace_whitespace (char *str)
{
int i;
By replacing whitespace with null terminators, you're changing the length of the string, thus this loop is useless. It will halt on the first whitespace character.
for (i = 0; i < strlen(str); i++)
if (isspace(str[i]))
str[i] = '\0';
}
Do you have to reverse the string in-place?
Even so, why not just replace the whitespace with null terminators and have an array of pointers to each of the tokens (in your array).
What I mean is:
Code:
zac@neux:code (1) $ gcc rev.c -o rev
zac@neux:code (1) $ ./rev
Token 1: This
Token 2: is
Token 3: an
Token 4: example
zac@neux:code (1) $ cat rev.c
#include <stdio.h>
#define MAX_WORDS 4
int main(void)
{
char str[] = "This is an example";
char * tokens[MAX_WORDS] = {NULL};
size_t i = 0;
size_t numberOfWords = 4; /* obviously you'd have to calculate this, and below at runtime */
tokens[0] = str; /* This */
str[4] = '\0';
tokens[1] = (str + 5); /* is */
str[7] = '\0';
tokens[2] = (str + 8); /* an */
str[10] = '\0';
tokens[3] = (str + 11); /* example */
for(i = 0; i < numberOfWords; ++i)
{
printf("Token %d: %s\n", i + 1, tokens[i]);
}
return 0;
}