c - Comparison of a Char Pointer to NULL -
i running code on suse linux. have pointer make = null in function. problem arises when try compare same pointer null in while loop. leading program crashing. have reproduced problem in sample code below. can please tell me happening here?
my code below:
#include <stdio.h> int func(char *,int); int main() { char buffer[20]; int =20; int temp = func(buffer,i); if ( (temp == 0) && (buffer != null) ) { printf("inside loop \n"); } } int func(char *ad,int a) { ad = null; printf("integer %d \n", a); return(0); }
the problem comparison, buffer != null
failing , control goes inside loop, should not happening ideally. have resolved this, doing this:
ad[0] = null
, comparison changed buffer[0] != null
.
since null used in pointer context, bad code. use '\0's instead of null in workaround , away not writing 'bad code', want know happening here. can please clarify?
thanks ton, aditya
buffer isn't pointer, cannot null.
your func
sets copied address of buffer null. not affect buffer @ all.
edit: extended explanation
char buffer[20];
this reserves 20 bytes somewhere on stack. they're not initialized in way. have 20 bytes of memory, these bytes must reside @ address.
int temp = func(buffer,i);
this takes address of 20 bytes in buffer, , passes func.
int func( char *ad,int a) { ad = null;
here have, @ new position on stack, new pointer variable exist while func
executing. pointer variable is at address, , points to address. change pointer, affects points. not change original buffer in way, since ad
temporary variable on stack contained address of bytes in buffer
variable (until set temporary variable null).
Comments
Post a Comment