-
March 27th, 2010, 11:47 AM
#1
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?
-
March 27th, 2010, 12:35 PM
#2
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
-
March 27th, 2010, 12:57 PM
#3
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.
-
March 27th, 2010, 01:00 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|