Reputation: 223
I have a question about type conversion in C.
So, I'm using these lines of code to initialize my index values to NULL:
frameTable[i].lv1Index = (int) NULL;
frameTable[i].lv2Index = (int) NULL;
where frameTable is constructed of the following:
typedef struct {
int lv2Index, lv1Index;
} Frame;
Frame* frameTable;
Can anyone tell me what is wrong with this?
This is my memory allocation:
frameTable = (Frame*) malloc(frameTableSize * sizeof(Frame));
Upvotes: 1
Views: 31861
Reputation: 109
In c, besides pointers you cannot set c objects to NULL. You cannot cast NULL to other object since it encapsulates nothing. So you might want to set your struct variables to 0 instead of NULL.
Upvotes: 0
Reputation: 231
This will probably compile and execute correctly since you're casting NULL to int (i.e., the compiler assumes you know what you're doing), but NULL is intended to be used with pointers. Since your structure fields are ints, just set them equal to zero to initialize them ("frameTable[i].lv1Index = 0;"). If you want to indicate that they are not valid indices yet, then set them to -1 or some other invalid value.
Upvotes: 3
Reputation: 477160
NULL
is a macro that represents the null pointer, not an integer. What you're doing is one of the most widespread and painful abuses that is causing the C++ standardisers no end of headache.
If you want an integer to be zero, use the octal 0
literal:
int n = 0;
Next, your code is fine, but missing the allocation. Where are the frameTable[i]
variables stored?
You need one of the following two:
Frame frameTable[2]; // automatic storage
Frame * frameTable = malloc(sizeof(Frame) * 2); // manual, your responsibility now
Upvotes: 5
Reputation: 2521
NULL is for pointers, not ints. While you can force the casting of just about anything, you're better off being more explicit and exact in setting them to 0.
You can also get the same effect by calloc'ing the memory (versus mallocing it) when you allocate your frameTable(s). Calloc clears all bytes to 0 in the memory that it allocates.
Upvotes: 3