Thread: Slightly complicated array&memory questions

  1. #1
    Registered User
    Join Date
    Mar 2002

    Slightly complicated array&memory questions

    I have a few questions about strings (char array, not the C++ class), and the way C++ automatically assigns (and deletes!) memory, but first I want to make sure my assumptions are right:
    When you declare a variable in a limited scope, it is deleted from memory as soon as the scope ends. So, when you declare a variable in a function, and return the contents of that variable from the function the actual variable is destroyed from memory, and the contents are sent through memory to the other variable it should be stored in.
    The questions:
    1. But when you declare a string like this:
     char *cString = "Some ugly 25 char string\0"
    it would also be destroyed at the end of the scope. However, when you return this, and place the pointer to the string in another variable, would it still be destroyed? And if it's destroyed, would it still be possible to copy the memory following the pointer that is returned to another string pointer?
    2. When you return a constant string, and set a pointer to the start of that string like this:
    char *function()
      return "Whee! Nifty constant string!";
    int main()
      char *Hark;
      cout << Hark << "\n";
    would that work? Will it work for non-constant strings, and should I delete Hark after using it? If not, how does C++ know it should delete it, and how do I know C++ knows?

    That's quite a few questions, and I'm totally clueless on this subject, so if anyone could help me out here, that'd be really cool! If someone knows of an on-line document about C++'s automatic memory that'd be even better though.
    Typing stuff in Code::Blocks 8.02, compiling stuff with MinGW 3.4.5.

  2. #2
    You did ask a lot of questions, and I do not have time now to answer them

    but it looks like you need to read up on scope, and passing by reference

    that should help to answer your questions

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. A very long list of questions... maybe to long...
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-16-2007, 05:36 AM
  3. Some questions about Status Bars/Menus...
    By AoA in forum Windows Programming
    Replies: 8
    Last Post: 07-30-2006, 11:36 PM
  4. Several Questions, main one is about protected memory
    By Tron 9000 in forum C Programming
    Replies: 3
    Last Post: 06-02-2005, 07:42 AM
  5. Trivial questions - what to do?
    By Aerie in forum A Brief History of
    Replies: 23
    Last Post: 12-26-2004, 09:44 AM