#include<stdio.h>
#include<stdlib.h>
#define MAX 256
int main()
{
char **ptr;
char input[MAX];
int i=0,j=0,k=0;
printf("Enter the string\n");
scanf("%[^\n]",input);
ptr=(char **)malloc(8+1);
if(ptr==NULL)
{
printf("ptr malloc: error\n");
return 0;
}
for(i=0;i<8;i++)
{
ptr[i]=(char*)malloc(MAX);
if(ptr[i]==NULL)
{
printf("malloc: Error\n");
return 0;
}
}
for(i=0;i<8;i++) {
k=0;
if(i!=0)
j++;
while(input[j]!=' ' && input[j]!='\0') {
ptr[i][k++]=input[j];
j++;
}
ptr[i][k]='\0';
}
for(i=0;i<8;i++)
printf("%s\n",ptr[i]);
return 0;
}
GDB traces:
(gdb) p j
$17 = 12
(gdb) n
31 ptr[i][k++]=input[j];
(gdb) p i
$18 = 4
(gdb) p k
$19 = 0
(gdb) p j
$20 = 12
(gdb) p input[j]
$21 = 119 'w'
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400625 in main () at kk.c:31
31 ptr[i][k++]=input[j];
Here, I am providing input as 9 words separated by one space. Till ptr[3] it is going smooth after that it got crashed. I want each pointer in double pointer to point to one word, later I want to calculate frequency of same word.
input : w1 w2 w3 w1 w4 w2 w3 w1 w1 ,it got crashed for i=4
Edit: I want output like this output : Each word in new line.