Input : Hello I am a newbie
Output: newbie a am I Hello
I am getting a segfault .On tracing i find it happens in the reverse
routine.
Can anyone help me fix it ?
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
void reverse(char **);
void print_2_array(char** array1 ,int row,int col);
void reverse(char **words)
{
if(*(words + 1) != '\0')
{
reverse((words + 1));
}
printf("%s",*(words + 0));
}
void print_2_array(char** array1 ,int row,int col)
{
int i, j;
for (i=0; i < row; i++)
{
for(j=0; j < col; j++)
printf("%c", array1[i][j]);
printf("\n");
}
}
int main() {
char line[200];
char **words;
int i = 0,j = 0,k = 0;
char* a =line;
words = (char**)malloc(10*sizeof(char*));
words[j] = (char*)malloc(15*sizeof(char));
memset(words[j],0,15*sizeof(char));
scanf("%[^\n]s",line);
for(; *a ;i++)
{
if(*a == ' ')
{
j++;
words[j] = (char*)malloc(15*sizeof(char));
memset(words[j],0,15*sizeof(char));
*(*(words + j) + k) = '\0';
k = 0;
}
*(*(words + j) + k) = *a;
k++;
a++;
}
*(*(words + j ) +k) = '\0';
print_2_array(words,j+1,15);
reverse(words);
}