我很长时间以来一直在摸不着头脑。
typedef struct B_{
/* something */
}B;
typedef struct A_{
B* pointB;
}A;
func1(A *pointA)
{
pointA->pointB = malloc(SOMESIZE);
}
function(A *pointA)
{
/* STATE 1
* pointA is perfectly allocated here and
* pointB inside pointA is NULL at this moment.
*/
func1(pointA);
/* STATE 2
* pointB is still NULL at this moment??
*/
}
在function()
中,参数pointA
是完全分配的结构,具有多个成员和指针pointB
,即NULL
。我正在调用另一个以pointA
为参数并分配pointB
的函数。我调试了pointB
malloc
之后的func1()
,但是当我从pointB
返回时,我仍然看到NULL
为pointA
。我认为这看起来像我传递{{1}}作为价值而不是参考,但我很难将这一点放到我的头脑中。我传递了一个完全有效的结构指针,其成员指针为NULL,并且我分配了该成员指针。
答案 0 :(得分:0)
我刚刚尝试了以下程序,请告诉我你的是否类似:
typedef struct B_{
/* something */
}B;
typedef struct A_{
B* pointB;
}A;
func1(A *pointA)
{
pointA->pointB = malloc(SOMESIZE);
printf("\nValue of pointB:%p\n", (void*)(pointA->pointB));
}
function(A *pointA) // Check in Debugger, For me this is coming as NULL
{
/* STATE 1
* pointA is perfectly allocated here and
* pointB inside pointA is NULL at this moment.
*/
pointA = (A*)malloc(sizeof(A));
if (pointA == NULL) {
printf("\nReturning NULL from malloc\n");
exit(0);
}
printf("\nValue of pointA:%p\n", (void*)pointA);
func1(pointA);
printf("\nValue of pointB:%p\n", (void*)(pointA->pointB));
/* STATE 2
* pointB is still NULL at this moment??
*/
}
int main()
{
A *pointA = NULL;
// Passing pointA as value from here, so it will be NULL after this call.
function1(pointA);
return 0;
}
这里,pointA作为值传递给function1(),因此从这个函数返回后,它仍然是NULL。所以,我认为调试器存在一些问题。
pointA的值:0xa39010
pointB的值:0xa39030
pointB的值:0xa39030