I've been working on a program that will take an array of pointers that contains multiple strings and print those strings out with the words in reverse order.
For example, if the array is:
Code:
char* str[] = {"one two three", "four five six"};
I want it to print out:
Code:
Words before reverse one two three
four five six
Words after reverse eno owt eerht
ruof evif xis
This is what I've come up with so far. Right now the code will execute, but the output is not as what I described above.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//char* strdup( const char*);
int words_reverse( char* str, char* words[], int maxwords );
int main(){
int i;
const char* str[] = {"one two three", "four five six"};
char* words[100];
const int NB_TESTS = 2;
printf("Words before reverse \t%s \n\n", str);
printf("Words after reverse \t");
for(i=0; i < NB_TESTS; i++){
char* input = (char*)_strdup(str[i]);
words_reverse(input, words, 100);
}
printf("\n\n");
system("pause");
return 0;
}
int words_reverse( char* str, char* words[], int maxwords ){
int i, j, k;
int start = 0;
for (i = 0; i <= strlen(str); i++){
if (!isalnum(str[i]))
{
k = 0;
for (j = start; j < i; j++){
words[k] = &str[j];
k++;
}
words[k] = '\0';
_strrev(words);
printf("%s ", words);
start = i + 1;
}
}
return 0;
}
Right now the code will execute, but the output is incorrect. I'm still a novice at C and I've always had difficulty with pointers and arrays. Can anyone help me out please?