Reputation: 11
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 ? I have already set list = &L
and L = NULL
.
Upvotes: 1
Views: 361
Reputation: 4951
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. 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).
Upvotes: 0
Reputation: 15121
Looks like you want to change (initialize) something pointed to by list
, here is how it usually be done:
void DocumentRowList_init(DocumentRow ** list) {
*list = ( DocumentRow * ) malloc( sizeof( DocumentRow ) );
if ( *list == NULL ) {
fatalError( "memory is not enough" );
}
}
Upvotes: 2
Reputation: 22084
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.
So even though you assign NULL
to it, it will point to invalid memory.
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.
If you want to return a structure of DocumentRow
you'd have to use this
*list = malloc( sizeof *L);
to allocate a structure and return the pointer to it.
Upvotes: 2