CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    A question regarding pointer

    Suppose we have definitions in the following,
    Code:
    void foo()
    {
        char s1[] = "Hello world";
    }
    
    void foo()
    {
        char* s2 = new char[100];
    }
    What is the difference between the memory allocation space for s1 and s2?

  2. #2
    Join Date
    Mar 2006
    Posts
    151

    Re: A question regarding pointer

    s1 is the static address of a 12 byte block (including the null terminator).

    s2 has the size "sizeof(char *)" (likely either 4 or 8). That address will dynamically contain the address of a 100-byte block existing elsewhere.

    That's why char ** x = &s2 is valid, but char ** x = &s1 will not compile.
    Last edited by GeoRanger; March 27th, 2010 at 12:37 PM. Reason: meant to say &s1

  3. #3
    Join Date
    Mar 2006
    Posts
    151

    Re: A question regarding pointer

    I should clarify. s1 is not a separate variable in your program. The 12 byte block exists and it has an address, but s1 is not declaring a separate variable to hold that address, so when you use s1 in your code the compiler directly uses the address of that 12 byte block.

    In contrast, s2 is declaring a completely separate variable (namely a pointer) to hold the address you assign to it.

    Thus, &s2 is valid because you have a separate variable and that variable has an address, while &s1 is not valid because s1 is the static-only address of that 12 byte block, that address is not stored in a separate variable in your program, and thus nothing exists from which "&s1" can take the address.

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: A question regarding pointer

    ---

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured