c - Given a string, store its substrings in a 2D array -
i asked write program, given string "acmprog", should generate , ordered set of substrings.
so here's code:
void gen_substrings(char a[],char sub[][100],int len){ int i,count=2; char first=a[0]; printf("%c",first); for(i=0;i<len-2;i++){ strncpy(sub[i],a,count); printf("%s\n",sub[i]); count++; } } main(){ char string[]={"acmprog"}; int len = sizeof(string); char substrings[len][100]; gen_substrings(string,substrings,len); system("pause"); }
when run it, output this:
when should be:
a ac acm acmp acmpr acmpro acmprog
what did wrong?
every time @ end of string have re-create null
for(i=0;i<len-2;i++) { strncpy(sub[j],a,count); //use different variable sub[j][count]='\0';// @ end , re-create null printf("%s\n",sub[j++]); count++; }
c
No comments:
Post a Comment