C语言alloc实现代码疑问:为何allocp可直接赋值为allocbuff?
allocp = allocbuff is Valid in C Great question! Let's break down exactly why this assignment works perfectly in C, using your alloc function code as context.
1. Array Names Implicitly Convert to Pointers (Most of the Time)
In C, when you use an array name like allocbuff in an expression (with a few specific exceptions), it automatically gets converted to a pointer to the array's first element.
So this line:
static char *allocp = allocbuff;
is exactly equivalent to writing:
static char *allocp = &allocbuff[0];
The compiler treats the array name as a pointer to its starting position behind the scenes.
2. Type Matching Makes the Assignment Legal
Let's check the types here:
allocbuffis an array ofchar(char[ALLOCSIZE]). When converted, it becomes achar *(pointer to a singlechar).allocpis declared as achar *variable.
Since both sides of the assignment are the same type (char *), C allows this operation without any issues. No type casting is needed here—this is standard, intended behavior in the language.
3. The Exceptions to the Array-Pointer Rule
Just to avoid confusion, there are a couple of cases where an array name doesn't convert to a pointer:
- When used with the
sizeofoperator:sizeof(allocbuff)returns the total size of the entire array (ALLOCSIZEbytes), not the size of a pointer. - When used with the address-of operator
&:&allocbuffgives a pointer to the entire array (typechar (*)[ALLOCSIZE]), which is a different type fromchar *and can't be directly assigned toallocp.
Why This Matters for Your alloc Function
This assignment sets allocp to point to the start of the allocbuff memory pool. As you call alloc(n) to request memory, allocp gets incremented by n to track the next free position in the array—this is a simple but effective way to manage a fixed-size block of memory manually.
内容的提问来源于stack exchange,提问作者sri harsha

