I'd like to make a list of most common problems that newbies to C are facing and possible solutions.
I'll start with:
Problems
1. fflush(stdin)
2. scanf() leaves newline ( related to 1 )
3. void main(void) vs int main(void)
4. not initializing variable before use
5. pointer vs array
6. scanf("%s",&array_name) ;
7. misplacing equality operator( == ) with assignment operator (=)
8. Off by One Error ( by Mk27)Code:if( i = 1 ) { /* trouble! */ if( 0 < n < 10 ) instead of if( n > 0 && n < 10) if (x == 5 || 6) instead of if (x == 5 || x == 6)
9.Code:char *copy = malloc(strlen(string)); /* forget +1 for null char*/ strcpy(copy,string);
SolutionsCode:foo_t *p; p = malloc( sizeof(*p) ); // good practice p = malloc( sizeof(foo_t) );
1. fflush(stdin)
2. same as 1
3. void main(void) vs int main(void)
4. Enable compiler warning (for gcc, use -Wall flag)
5. pointer vs array
6. scanf("%s",&array_name);
7. Enable compiler warning.
8.
9. The former method is less accident prone, and is easier to maintain (ie: you don't have to ever change it). If you go back and substitute foo_t for bar_t, you have to chase down all of your malloc calls, and change them too. If you use the first method, you don't have to. ( By quzah )
Please feel free to add other problems you could think of.