Initializing structure member( char array)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thokadess
    New Member
    • Sep 2006
    • 3

    Initializing structure member( char array)

    I have declared an char array in my structure.After creating instance of the structure,i initialized its members in following way.

    structure student
    {
    char name[20];
    int rol_no;
    }

    int main()
    {
    student s1;
    s1.name = "jimmy";
    // some more statements..
    }

    this code gives me compilation error as "lvalue required before '=' operator "

    Can anyone please explain me why??
  • pukur123
    New Member
    • Sep 2006
    • 61

    #2
    As soon as you declare the variable of the structure, it takes memory. So it will take the memory for the array s1.name and the base address of this array get stored in s1.name.

    Now the statement

    s1.name = "jimmy";

    is trying to change the base address of the array which is not possible.

    Instead you use the strcpy(s1.name, "jimmy").

    Let's analyse the following code.

    char s[10];
    s="jimmy";

    Here s is an array of 10 characters. So in 10 bytes of memory will be allocated for storing the characters and we know that the base address will be stored in s.

    Let us suppose that the base adress of the array be 100 and so it is get stored in s.

    But when you print the size of the array it shows that 10 bytes have been occupied by this array. Then where did the s get stored, i.e., the base address 100 get stored.

    So it means that it does not take any space for storing the base address of the array and the statement

    s="jimmy";

    is trying to change the base address of the array.

    Comment

    • thokadess
      New Member
      • Sep 2006
      • 3

      #3
      Thanks for ur reply..

      Comment

      Working...