unable to store as array of strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sivakumar Kotamraju
    New Member
    • May 2007
    • 6

    unable to store as array of strings

    Hi ,

    I am unable to store the words in a string as array of strings.Could any body comment on this?

    void func(char *s) {
    int length;
    char c;
    char **a;
    int i,j,l;
    int k=0,count=0;
    length=strlen(s );
    a=(char **)malloc(2*siz eof(char *));
    for(i=0;i<2;i++ )
    a[i]=(char *)malloc(5);
    for(i=0;i<lengt h;i++) {
    c=s[i];
    if(c==' ') {
    j=i-1;
    for(l=j;l>=k;l--)
    a[count][l]=s[l];
    a[count][j-k+1]='\0';
    printf("%s\n",a[count]);
    k=i;
    count++;
    }
    }
    for(i=0;i<count ;i++) {
    printf("%s\n",a[i]);
    }
    }


    int main() {
    char *s="siva kumar";
    printf("The given string is %s\n",s);
    func(s);
    return 0;
    }
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Hi,
    the problem is in ur logic in this part

    Code:
    for(l=j;l>=k;l--) 
    a[count][l]=s[l];
    In the first iteration u will get the string properly.
    In the second iteration u start filling the string from the value 4/5 not from 0( with the example u have given)
    Try to change this logic

    NOTE:Please use code tags while posting

    Raghuram

    Comment

    • Sivakumar Kotamraju
      New Member
      • May 2007
      • 6

      #3
      Originally posted by gpraghuram
      Hi,
      the problem is in ur logic in this part

      Code:
      for(l=j;l>=k;l--) 
      a[count][l]=s[l];
      In the first iteration u will get the string properly.
      In the second iteration u start filling the string from the value 4/5 not from 0( with the example u have given)
      Try to change this logic

      NOTE:Please use code tags while posting

      Raghuram
      Hi Raghu,

      in each interation iam going from back to front of a word while storing into a array of strings form.

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        Originally posted by Sivakumar Kotamraju
        Hi Raghu,

        in each interation iam going from back to front of a word while storing into a array of strings form.

        I understood the logic.
        But while getting the second string you are start filling the value from the end of the string to the position 5(That is is l value is 5).
        U are doing a memory overwrite.

        Raghuram

        Comment

        Working...