What's wrong with my code.

Discussion in 'Programmer's Corner' started by asdf arfw, Oct 21, 2017.

  1. asdf arfw

    Thread Starter Member

    Sep 9, 2017
    43
    0
    What's wrong. I can't find out.

    upload_2017-10-22_2-57-52.png
     
  2. AlbertHall

    AAC Fanatic!

    Jun 4, 2014
    7,649
    1,868
    In line 13 you can't assign strings like that. You need to use strcpy. See particularly line 11 here.
     
  3. asdf arfw

    Thread Starter Member

    Sep 9, 2017
    43
    0
    It works. Thanks for your help.
    But I'm still wondering why we can't assign strings like that in the function?
     
  4. AlbertHall

    AAC Fanatic!

    Jun 4, 2014
    7,649
    1,868
  5. nsaspook

    AAC Fanatic!

    Aug 27, 2009
    5,706
    6,414
    Because it's an array not a C++ string. http://www.lysator.liu.se/c/c-faq/c-2.html

    st[0].name will be treated like a pointer. In C++ using std::string instead of an array should work.

    std::string name ="zztop";// initialization works
    name="zztop";// assignment works
     
  6. spinnaker

    AAC Fanatic!

    Oct 29, 2009
    7,815
    3,672

    In C++ or BASIC you can.
     
  7. WBahn

    Moderator

    Mar 31, 2012
    24,125
    7,491
    The basic problem is that when you created this global variable st, you created as an array of structures that is located at a specific place in memory that was allocated for it.

    Let's say that each data structure of type 'student' takes 44 bytes of data. So when you declared st[3] the memory manager allocated 132 bytes of memory. Let's say that the base address of this block is at address 1000.

    That means that st[0] starts at 1000, st[1] starts at 1044, and st[2] starts at 1088.

    Within those, name is the 30 bytes at the very beginning, so

    st[0].name is at address 1000.

    This is a constant address. You can't change it. It needs to allows point to THAT memory location, otherwise it is not within the st[0] data structure.

    The string "Patrick is a stupid guy" is a string literal that is, most likely, stored someplace as part of the code itself. Perhaps that string is located at address 5440. The string, like all such strings, evaluates to the address at which it is stored. So you statement tries to get st[0].name to point to address 5440, but that would result in it pointing to a location other than where it HAS to point -- so the compiler throws an error.
     
Loading...