在局部函数中,我想计算图中有多少个节点相互指向(入度),它由相邻列表表示。奇怪的是,当我在这个函数中打印时,我所有的数字都是正确的,但是当我从函数中传出时,我丢失了一半。
VertexType *InDegree( Graph G )
{
int Size, i;
Size = G->GraphSize; // Size is 17
VertexType *degree;
for (i = 0; i < Size; ++i)
degree[ i ] = 0;
for (i = 0; i < Size; ++i)
{
VertexNodePtr P;
P = G->Vertices[ i ].AdjList;
// A traverse, not relevant to this question
while (P != NULL)
{
++degree[ P->Vertex ];
P = P->Next;
}
}
// here I can print all the numbers using a
// for-loop counting to 17, correctly.
// but sizeof() gives me half the length I expect!
// which is 8. And out of this function counting to
// 17 causes an overflow.
return degree;
}
最佳答案
sizeof
是一个无法确定动态分配数组(或衰减为指针的静态数组)大小的运算符。结果为 8,因为您可能是在指针类型(例如 VertexType*
)上计算它,它返回指针的字节大小,在 64 字节架构中为 8 字节。
在这种特定情况下忽略 sizeof
的结果,在处理数组时,它能够只计算静态(或本地数组)的总字节数。
关于C - 指向 int 的局部指针丢失了一半大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275734/