我觉得我对指针的理解有点困难。
我似乎无法遵循这段代码的逻辑:
typedef struct StackRecord
{
int Capacity;
int TopOfStack;
int* Array;
}*Stack;
在下面的结构中,*Stack被声明通过简单地声明Stack来接收StackRecord结构类型的地址,因为typedef
但下面的代码返回StackRecord结构类型的另一个地址接收器。为什么不回地址?而是返回相同类型的指向自身的指针?
Stack CreateStack(int MaxElements)
{
Stack S;
if (MaxElements < MinStackSize)
{
printf("Error : Stack size is too small");
return 0;
}
S = (Stack)malloc(sizeof(struct StackRecord));
if (S == NULL)
{
printf("FatalError : Out of Space!!!");
return 0;
}
S->Array = (int*)malloc(sizeof(char)* MaxElements);
if (S->Array == NULL)
{
printf("FatalError : Out of Space!!!");
return 0;
}
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
最佳答案
不管你信不信,去掉typedef可能会让事情变得更清楚一点:
struct StackRecord
{
int Capacity;
int TopOfStack;
int* Array;
};
/**
* Return a pointer to a new, dynamically allocated instance
* of struct StackRecord
*/
struct StackRecord *CreateStack(int MaxElements)
{
struct StackRecord *S;
if (MaxElements < MinStackSize)
{
printf("Error : Stack size is too small");
return 0;
}
S = malloc(sizeof *S); // no need for cast, sizeof *S is same as sizeof (struct StackRecord)
if (S == NULL)
{
printf("FatalError : Out of Space!!!");
return 0;
}
/**
* Allocate the memory for the Array member of
* the new stack record instance.
*/
S->Array = malloc( sizeof *S->Array * MaxElements );
if (S->Array == NULL)
{
printf("FatalError : Out of Space!!!");
return 0;
}
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
在您发布的代码中,
Stack
基本上是struct StackRecord *
的同义词。函数使用struct StackRecord
创建malloc
的新实例,初始化该记录的内容,并返回指向该新实例的指针。关于C中的
malloc
调用,您不需要强制转换malloc
的结果,这样做通常被认为是不好的做法1。此外,sizeof
的操作数不必是类型名,它可以是要分配的类型的表达式。听着,给我一个声明T *p;
sizeof (T)
和sizeof *p
都做同样的事情-表达式*p
具有类型T
。所以malloc调用的一般形式可以写成T *p = malloc( sizeof *p * N );
或
T *p;
...
p = malloc( sizeof *p * N );
它比
p = (T *) malloc( sizeof (T) * N );
对于C++来说,这是不正确的,因为C++不允许C方式和其他指针类型之间的隐式转换。但是,如果你正在编写C++,无论如何你不应该使用
void *
。