C Mistakes – 1D array

Array is one of the important concept in c programming, while learning or practicing 1D Array most of the beginners unknowingly follow incorrect or invalid syntax of array. This tutorial will list out 1D Array : Mistakes in C Programming

C Programming 1D Array : Mistakes

Mistake 1 : Constant Expression Require

#include<stdio.h>
void main()
{
int i=10;
int a[i];
}

Consider the above example of 1D Array,

  1. We are going to declare an array whose size is equal to the value of variable.
  2. If we changed the value of variable then array size is going to change.
  3. According to array concept, we are allocating memory for array at compile time so if the size of array is going to vary then how it is possible to allocate memory to an array.

i is initialized to 10 and using a[i] does not mean a[10] because ‘i’ is Integer Variable whose value can be changed inside program.

Value of Const Variable Cannot be changed

we know that value of Const Variable cannot be changed once initialized so we can write above example as as below -

#include<stdio.h>
void main()
{
const int i=10;
int a[i];
}

or

int a[10];

Recommanded Article : Compile Time Initializing an Array

Mistake 2 : Empty Valued 1D Array

#include<stdio.h>
void main()
{
int arr[];
}

Consider the above example, we can see the empty pair of square brackets means we haven’t specified size of an 1D Array. In the example array ‘arr’ is undefined or empty.

Size of 1D Array should be Specified as a Constant Value.

Instead of it Write it as -

#include<stdio.h>
void main()
{
int a[] = {1,1};
}

above syntax will take default array size equal to 2. [Refer Article : Section B]

#include<stdio.h>
void main()
{
int a[] = {}; // This also Cause an Error
}

Mistake 3 : 1D Array with no Bound Checking

#include<stdio.h>
void main()
{
int a[5];
printf("%d",a[7]);
}
  1. Here Array size specified is 5.
  2. So we have Access to Following Array Elements - a[0],a[1],a[2],a[3] and a[4]
  3. But accessing a[5] causes Garbage Value to be used because C Does not performs Array Bound Check.

If the maximum size of array is “MAX” then we can access following elements of an array -

Elements accessible for Array Size "MAX" = arr[0]
                                         = .
                                         = .
                                         = .
                                         = arr[MAX-1]

Mistake 4 .Case Sensitive

#include<stdio.h>
void main()
{
int a[5];
printf("%d",A[2]);
}

Array Variable is Case Sensitive so A[2] does not print anything it Displays Error Message : “Undefined Symbol A

C Programming 1D Array Tips

Tip 1 : Use #define to Specify Array Size

#include<stdio.h>
#define MAX 5
void main()
{
int a[MAX];
printf("%d",a[2]);
}
  • As MAX is replaced by 5 for every Occurrence , So In due Course of time if you want to increase or decrease Size of array then change should be made in
#define MAX 10

Tip 2 : a[i] and i[a] are Same

Visit this article which will explain how to access array randomly using a[i] and i[a].

C Pointer Mistake

In this chapter we will learn about common Pointer Mistake that programmer does while writing pointer in C Programming.

C Programming Pointer Mistake

We all know that pointer is used to store the address of a variable. Pointer Variable stores the address of variable.Below are some of the common mistakes committed by Novice programmer.

Pointer Mistake 1 : Assigning Value to Pointer Variable

int * ptr , m = 100 ;
      ptr = m ;       // Error on This Line

Correction :

  1. ptr is pointer variable which is used to store the address of the variable.
  2. Pointer Variable “ptr” contain the address of the variable of type ‘int’ as we have declared pointer variable with data type ‘int’.
  3. We are assigning value of Variable to the Pointer variable, instead of Address.
  4. In order to resolve this problem we should assign address of variable to pointer variable

Write it like this -

ptr = &m ;

Pointer Mistake 2 : Assigning Value to Uninitialized Pointer

We are assigning the value to the pointer variable. We all know that pointer is special kind of variable which is used to store the address of another variable. So we can store only address of the variable to the pointer variable.

int * ptr , m = 100 ;
*ptr = m ;            // Error on This Line

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.

Pointer Mistake 3 : Not De-referencing Pointer Variable

De-referencing pointer is process of getting the value from the address to whom pointer is pointing to.

int * ptr , m = 100 ;
ptr =  &m ;
printf("%d",ptr);     

In the above example, You will not get any compiler or run time error but it is considered as common mistake by novice user to de-reference pointer variable without using asterisk (*)

Pointer Mistake 4 : Assigning Address of Un-initialized Variable

int *ptr,m;
ptr = &m;     

Best practice while using pointer is to initialize pointer before using it.

We can assign any valid address to pointer variable but if you assign the address of un-initialized variable to pointer then it will print garbage value while de-referencing it.

Re-commanded Article : How storage class determines the default initial value

Pointer Mistake 5 : Comparing Pointers that point to different objects

We cannot compare two pointer variables. Because variables may have random memory location. We cannot compare memory address.

char str1[10],str2[10];
char *ptr1 = str1;
char *ptr2 = str2;
if(ptr1 > ptr2)  .....   // Error Here
{
....
....
}

C if-else mistake

We have already studied the if-else statement in c programming. In this chapter we will be learning common if-else mistake committed by novice programmers.

C Programming if-else mistake

If-else mistake 1 : Assignment operator and comparison operators

Basic if-else mistake committed by the novice user is use of assignment operator in if statement instead of the comparison operator.

Assignment operator = is used for assigning value to variable while comparison operator == checks whether LHS and RHS entries are same or not

if(var = 10)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

Consider above program, if we use assignment operator in if statement then value 10 will be assigned to variable var. Any non-zero number inside if condition is considered as true condition so it will always executes to true

if(var = 0)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

however above statement executes to be false as we are assigning 0 to variable. Best practice of using if statement is -

if(var == 10)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

In if statement use == instead of =

If-else mistake 2 : Use of Semicolon

In C Programming, we use semicolon as termination character. Same case is applicable for if statement. Semicolon after the if statement will terminate if statement

Consider the below program -

if(var == 10);
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

above program would execute statement 1..4 without any issue because semicolon at the end of if statement makes if-statement bodyless. Compiler will expand above program as -

if(var == 10) {
}
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

Use of semicolon after if statement does not throw compile error. It will execute if statement without any issue.

If-else mistake 3 : Else without using if

Using the else statement without if will throw compile error because each time if and else must come in pair with else as optional part.

Statement1 ;
Statement2 ;
..
   else
     {
     Statement 3;
     Statement 4;
     .
     .
     }
}

compiler will throw an error message - Misplaced Else. Important rule of thumb is that each else must have corresponding if

If-else mistake 4 : Opening and Closing Braces

Statement1 ;
  if(condition)
Statement1 ;
Statement2 ;
else
{
Statement 3;
Statement 4;
}

Explanation :

  1. If multiple Statements within if must be wrapped in Pair of braces.
  2. Error Message : Misplaced else
  3. Statement1 and statement2 must be wrapped inside if
  4. Here only Statement1 is the part of if
if(condition)
     {
     Statement1 ;
     Statement2 ;
     }
   else
     {
     Statement 3;
     Statement 4;
     }

Common C Programming Mistakes : Preprocessor Errors

Preprocessor processes given source code before giving it to the compiler.Preprocessor must be used with care. Some of the Common mistakes while using preprocessor are as below -

Mistakes while writing C Preprocessor directives :

Macro expansion should be enclosed within parenthesis

#include<stdio.h>
#include<conio.h>
#define SQU(x) x*x
void main()
{
int num ;
clrscr();
num = SQU(2)/SQU(2);
printf("Answer : %d",num);
getch();
}

Output :

Answer : 4

Explanation of Program :
Above expression will be expanded as -

SQU(x) / SQU(x) = [ x*x / x*x]
                = [ x*x/x*x  ]
                = [   x*x    ]
                = [   x^2    ]

In the program the macro #define substitutes SQU(2) by just 2*2 not by 4. thus -

SQU(2) / SQU(2) = [ 2*2 / 2*2]
                = [ 2*2/2*2  ]
                = [   2*2    ]
                = [   2^2    ]
                = [    4     ]

In order to avoid the above problem we can write like -

#define SQU(x)((x)*(x))

Do not Leave blank between macro-template and its argument

#define SQU(x)((x)*(x))//Write like this
  • Do not give space between SQU and (x) , as it becomes the part of macro expansion
  • It results into Improper result OR Compile time Error

Do not Give semicolon at the end of #define statement .

#define SQU(x)((x)*(x));//Do not give semicolon at the end

Allot one line for each macro preprocessor

#include<stdio.h>
#include<conio.h>// Write on separate line

Do not write like this

#include<stdio.h>#include<conio.h>

C Mistakes – printf

1 : Missing Comma .

  • Comma is missing between format specifier(“%d”) and Variable (number).
  • Error message : ” Function call missing )
#include<stdio.h>
void main()
{
int number = 10;
printf("%d"number);
        //Error it should be written as : printf("%d",number);
}

2 : Write Correct Spelling of printf.

  • By mistake , many beginners misspelled “printf” as “print”.

3 : Check for Cases

  • C Programming is known as “Case Sensitive Language “.
  • “printf” should be written in small case [Lowercase]

4 : Format specifiers and Variable names should appear in Order

.

#include<stdio.h>
void main()
{
int number1 = 10;
float number2 = 3.14;
printf("%d %f",number2,number1);
}
  • Here “%d” is written first so “number1” should be written immediately after Comma.
  • Check for type i.e “%d” is written for “integer” and “%f” for “float”.

C Mistakes – scanf

Common Mistakes : Scanf Errors


1 : Don’t forget to write “&” before variable name

#include<stdio.h>
void main()
{
int num;
//Incorrect Way : scanf("%d",num); 
scanf("%d",&num);
}
  • Syntactically it won’t show any error message
  • Logically It shows you “Garbage” or “Unexpected Value”.
  • “&” should be written before “Variable” name .

2 : Don’t write “&” before Pointer variable

#include<stdio.h>
void main()
{
int num;
int *ptr;
ptr = #
//Incorrect Way : scanf("%d",&ptr;); 
scanf("%d",ptr);
}
  • Pointer variable Stores address of variable where it points .
  • “&” is used to access “Address of Variable” , therefor no need to write “&” before pointer variable .
  • Pointer stores the address of another variable , it accesses variable directly.