Posts

Showing posts from April, 2012

Common mistakes in C programming

Common mistakes about subfunction: 1. Formal parameter issues:   void GetMemory(char *p) { p = (char *)malloc(100); } void Test(void) { char *str = NULL; GetMemory(str);   strcpy(str, "hello world"); printf(str); } Using a pointer variable as formal parameter is dangerous, because formal parameter only passes the value. So it only pass the address.  So when allocate memory to formal paramter or any other defined pointer variables in subfunction, it will disapear after the end of subfunction. Insteadly, we can achieve the same function by passing the pointer variable who points the pointer variable who is going to be allocated. void GetMemory2(char **p, int num) { *p = (char *)malloc(num); if(*p==NULL) printf(" Memory allocation fails!\n "); } void Test(void) { char *str = NULL; GetMemory(&str, 100); strcpy(str, "hello");   printf(str);    } 2. Variable life in subfunction: ...

Pointer variable

Usually, pointer variables are with type difinition like  char * ,  int * ,  long * , and like that. So when you want to  do some operations, compiler will use  sizeof(type)  as the unit. For example: #include "stdio.h" main() {     int a[3]={4, 5, 6};     int *point1;     point1=a;     point1=point1+1;     printf("%d\n", *point1);     getchar(); } Result: 5 However, we can use  void *  to define  a point variable without type . But this variable cannot be operated because of the  uncertain length of this variable . So before operation, you have to  cast the variable to a specific type  to do the operations. For example: #include "stdio.h" main() {     int a[3]={4, 5, 6};     void *point2;     point2=a;     point2=(char *)point2+1;  ...