I am trying to reverse the words of the string (not the words itself). I am trying to dynamically allocate 2 dimensional array only using pointers(not using array syntax). My program compiles fine but end up displaying only one word as output with spaces here and there. Here is my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void rev(char *x, int n);
int words(char * p);
int main()
{
char *p = (char *)malloc(101*sizeof(char));
fgets(p, 101, stdin);
rev(p, words(p));
free(p);
return 0;
}
void rev(char *x, int n)
{
char **y = (char **)malloc(101*sizeof(char *));
int i = 0;
int *j = (int *)calloc(101, sizeof(int));
*y = (char *)malloc(101*sizeof(char));
while(*x!='\n')
{
if(*x==' ')
{
i++;
*(y+i) = (char *)malloc(101*sizeof(char));
}
else
{
*(*(y+i)+(*(j+i))) = *x;
(*(j+i))++;
}
x++;
}
i++;
int z, q;
for(z=i-1; z>0; z--)
{
for(q=0; q<(*(j+i)); q++)
{
printf("%c", *(*(y+z)+(q)));
}
printf(" ");
}
for(q=0; q<*j; q++)
{
printf("%c", *(*(y)+(q)));
}
printf("\n");
for(q=0; q<i; q++)
{
free(y+i);
}
free(j);
free(y);
}
int words(char * p)
{
int x = 0;
while(*p!='\n')
{
if(*p==' ')
{
x++;
}
p++;
}
return ++x;
}
I want to do it only using pointer arithmetic. I have been trying it for past 20 hours and couldn't figure it out. Can anybody explain the mistake and how to correct it?
Input
Hello World
Output
Hello
Input
This is my input
Output
This