Pointer to String and memory status

This is a discussion on Pointer to String and memory status within the C Programming forums, part of the General Programming Boards category; Hello I'm studying C and I have a question concerning the use of strings in C. If I have the ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    2

    Question Pointer to String and memory status

    Hello

    I'm studying C and I have a question concerning the use of strings in C.

    If I have the following code:

    char *string;

    string = "Hello";
    string = "I have a question";


    What's happens with the reserved memory for the string?
    - In the first atribution (string = "Hello") we will reserve memory for this string
    - In the second atribution what's happens with the memory? Is it the previous memory space for the previous string deleted and a new one is created?

    Thanks for any help

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The only memory "reserved" for string is the size of a pointer. When you do string = "Hello", then you set that pointer to point to a piece of memory that holds 'H', 'e', 'l', 'l', 'o', '\0'. Next when you set it to a different string, the pointer is set to a different memory location, where the new string is. The "Hello" string will still remain where it was in memory - you just have no way to find out were that is.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jul 2008
    Posts
    2
    ahh ok I understood.
    Thanks for your quick and nice answer

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 04:36 AM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 01:56 PM
  3. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  4. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 10:37 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21