Segfault in Recursion

N

Newbie

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[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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top