if(ptr == NULL){ // code if pointer is NULL} else { // code if not NULL}
if(ptr == NULL){ // code if pointer is NULL} else { // code if not NULL}
if (ptr != NULL) { // code if not NULL}
This looks a little awkward to some programmers, but it’s perfectly valid. Which approach you use just depends on personal preference, and how good your compiler is at detecting the if (ptr = NULL) error.
This looks a little awkward to some programmers, but it’s perfectly valid. Which approach you use just depends on personal preference, and how good your compiler is at detecting the if (ptr = NULL) error.
The reverse of this is if (!ptr), which will return TRUE if ptr is FALSE.
The reverse of this is if (!ptr), which will return TRUE if ptr is FALSE.
Avoid this mistake:char *ptr;if(ptr == NULL){//This will return FALSE. The pointer has been assigned a valid value. } Instead write:char *ptr = NULL; //This assigns the pointer to NULLif(ptr == NULL){//This will return TRUE if the pointer has not been reassigned. }
int *ptr = malloc(N * sizeof(int));if (ptr) { int i; for (i = 0; i < N; ++i) ptr[i] = i;}
int *ptr = malloc(N * sizeof(int));if (ptr) { int i; for (i = 0; i < N; ++i) ptr[i] = i;}