pointer to char

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maryan
    New Member
    • Feb 2008
    • 15

    pointer to char

    Hello,

    i have the following code:

    typedef struct
    {
    char *matrikelnr;
    }student;


    int main (void)
    {

    student *studall[2];
    char tVal[10];

    studall[0] = (student*)mallo c(sizeof(studen t));
    strcpy(tVal,"12 345");
    studall[0]->matrikelnr = tVal;
    printf("studall[0]->matrikelnr: %s\n",studall[0]->matrikelnr);

    studall[1] = (student*)mallo c(sizeof(studen t));
    strcpy(tVal,"12 346");
    studall[1]->matrikelnr = tVal;
    printf("studall[1]->matrikelnr: %s\n",studall[1]->matrikelnr);

    printf("studall[0]->matrikelnr: %s\n",studall[0]->matrikelnr);

    return 0;
    }

    output:

    studall[0]->matrikelnr: 12345
    studall[1]->matrikelnr: 12346
    studall[0]->matrikelnr: 12346

    My Question: How can i get for stuall[0] the first value 12345? Could any one please help me.

    thanks in advance.
    Maryam
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Originally posted by Maryan
    studall[0]->matrikelnr = tVal;
    Stop changing matrikelnr.

    matrikelnr is a char pointer. tVal is also a char pointer. (Remember, the name of an array is the address of element 0 and tVal[0] is a char). In effect all of your array elements point to tVal so they all report the final value placed in tVal.

    What you need to to is copy the tVal array to matrikelnr. That means you a) need to allocate memory for the copy and b) actually copy the array instead of just assigning its address.

    Comment

    • Maryan
      New Member
      • Feb 2008
      • 15

      #3
      Thank you for answering my Question. I have done it like this:

      typedef struct
      {
      char *matrikelnr;
      }student;


      int main (void)
      {

      student *studall[2];

      char *tVal;
      studall[0] = (student*)mallo c(sizeof(studen t));

      tVal=(char*)mal loc(10);
      strcpy(tVal,"12 345");
      studall[0]->matrikelnr = tVal;
      printf("studall[0]->matrikelnr: %s\n",studall[0]->matrikelnr);

      studall[1] = (student*)mallo c(sizeof(studen t));

      tVal=(char*)mal loc(10);
      strcpy(tVal,"12 346");
      studall[1]->matrikelnr = tVal;
      printf("studall[1]->matrikelnr: %s\n",studall[1]->matrikelnr);

      printf("studall[0]->matrikelnr: %s\n",studall[0]->matrikelnr);
      return 0;
      }

      and it works.

      bye,
      Maryan

      Comment

      Working...