Common Mistakes / Errors while using Pointer in C Programming
1 . Assigning Value to Pointer Variable
int * ptr , m = 100 ; ptr = m ; // Error on This Line
Correction :
- ptr is pointer variable
- “ptr” contain the address of the variable of type ‘int’
- We are assigning value of variable to the pointer variable, instead of address
- In order to resolve this problem we should assign address of variable to pointer variable
Write it like this -
ptr = &m ;
2 .Assigning Value to Uninitialized Pointer
int * ptr , m = 100 ; *ptr = m ; // Error on This Line
- “ptr” is pointer variable.
- “*ptr” means “value stored at address ptr“.
- We are going to update the value stored at address pointed by uninitialized pointer variable.
Instead write it as -
int * ptr , m = 100 ,n = 20; ptr = &n; *ptr = m ;
- Firstly Initialize pointer by assigning the address of integer to Pointer variable.
- After initializing pointer we can update value.”.
3 .Not Dereferencing Pointer Variable
int * ptr , m = 100 ; ptr = &m ; printf("%d",ptr); // Error on this Line
4. Assigning Address of Un-initialized Variable
int *ptr,m; ptr = &m; // Error on this Line
5. Comparing Pointers that point to different objects
char str1[10],str2[10]; char *ptr1 = str1; char *ptr2 = str2; if(ptr1>ptr2) ..... // Error Here
good work! could have been better if you posted the corrections too.
I will post corrections soon..