[英]How to set a pointer to struct to NULL
typedef struct _DocumentRow
{
char * code /** The code */;
char * designation /** The designation */;
double quantity /** The quantity */;
char * unity /** The unity */;
double basePrice /** The base price */;
double sellingPrice /** The selling price */;
double discount /** The discount */;
double rateOfVAT /** The rate of VAT */;
struct _DocumentRow * next /** The pointer to the next row */;
} DocumentRow;
void DocumentRowList_init(DocumentRow ** list) {
DocumentRow *L;
list = ( DocumentRow ** ) malloc( sizeof( DocumentRow* ) );
if ( list == NULL ) {
fatalError( "memory is not enough" );
}
L = NULL;
list = &L;
}
After using the function DocumentRowList_init
, when I test if ( *list == NULL )
, it evaluates to false, why ? 使用函数
DocumentRowList_init
,当我测试if ( *list == NULL )
,它的计算结果为false,为什么? I have already set list = &L
and L = NULL
. 我已经设置了
list = &L
和L = NULL
。
Looks like you want to change (initialize) something pointed to by list
, here is how it usually be done: 看起来您想更改(初始化)
list
指向的内容,这是通常的操作:
void DocumentRowList_init(DocumentRow ** list) {
*list = ( DocumentRow * ) malloc( sizeof( DocumentRow ) );
if ( *list == NULL ) {
fatalError( "memory is not enough" );
}
}
You would have undefined behaviour here. 您将在此处具有未定义的行为。
L
is a local variable, so when you return it's address via the pointer pointer, the variable no longer exists when DocumentRowList_init
is returning. L
是局部变量,因此当您通过指针指针返回它的地址时,当DocumentRowList_init
返回时该变量不再存在。
So even though you assign NULL
to it, it will point to invalid memory. 因此,即使您为其分配了
NULL
,它也将指向无效的内存。
But list
is local to DocumentRowList_init
, so it will not return the value anyway, as you only assign it a value and then return. 但是
list
对于DocumentRowList_init
是本地的,因此无论如何它都不会返回该值,因为您只为其分配了一个值然后返回。
If you want to return a structure of DocumentRow
you'd have to use this 如果要返回
DocumentRow
的结构,则必须使用此结构
*list = malloc( sizeof *L);
to allocate a structure and return the pointer to it. 分配结构并返回指向它的指针。
void DocumentRowList_init(DocumentRow ** list) {
DocumentRow *L;
list = ( DocumentRow ** ) malloc( sizeof( DocumentRow* ) );
if ( list == NULL ) {
fatalError( "memory is not enough" );
}
L = NULL;
list = &L;
}
Please mind that list=&L assigns list the address of a variable located on the stack. 请注意,list =&L为list分配位于堆栈上的变量的地址。 So once you exist the function the variable is out of scope and your list is left pointing to a some location (on the stack).
因此,一旦函数存在,变量将超出范围,列表将指向某个位置(堆栈上)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.