pointer to char array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nishantporwal
    New Member
    • May 2012
    • 1

    #1

    pointer to char array

    Program : -

    #include<iostre am.h>
    char *fl[5]={0};
    void print1();

    void main()
    {
    char p[3]="";
    int lng=52;
    for (int j=0; j<=strlen("thin k") ;j++ , lng++ )
    {
    sprintf(p,"%d", lng);
    fl[j]=p;
    cout<<"Value in loop is--> " << fl[j]<<endl;
    }
    print1();
    }

    void print1()
    {
    for(int i=0; i<=5; i++)
    cout <<"Value after--> "<<fl[i]<<endl;
    }



    Output : -

    ./123
    Value in loop is--> 52
    Value in loop is--> 53
    Value in loop is--> 54
    Value in loop is--> 55
    Value in loop is--> 56
    Value in loop is--> 57
    Value after--> 57
    Value after--> 57
    Value after--> 57
    Value after--> 57
    Value after--> 57
    Value after--> 57


    Issue : - Statement fl[j]=p; is setting all the elements of the array as the same value , pl help !!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You only have one array p.

    You assign p to every element of f.

    Therefore, the last value you put in p will appear as the value for
    every element of f.

    You need to allocate a new p array for every element of f. Then you will be able to aev searate values for every f element.

    Comment

    Working...