Home Interview Preparation C Interview Questions

C Interview Questions

by anupmaurya
335 minutes read
C Interview Questions

In this article you we will learn C Interview Questions that are mostly frequently asked in the interview.

C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions.

Q1. What is a token in C?

In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a C program, the smallest individual units are known as C tokens has six types of tokens:

  • Keywords: C keywords are the words that convey a special meaning to the c compiler. The keywords cannot be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed.Example: auto, break, int, long, for etc.
  • Identifiers: Identifiers are used as the general terminology for the names of variables, functions and arrays.
  • Constants: C constants refers to the data items that do not change their value during the program execution.
  • Special Symbols : Symbols other than the Alphabets and Digits and white-spacesExample: = ,{} etc.
  • Operators: An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language provides the following types of operators −
    1. Arithmetic Operators
    2. Relational Operators
    3. Logical Operators
    4. Bitwise Operators
    5. Assignment Operators
    6. Misc Operators

Q2. What are the storage classes in C?

C have the following classes storage auto, register, external, and static.

Auto: In the language C auto is a keyword for specifying a storage duration. When you create an auto variable it has an “automatic storage duration”. We call these objects “local variables”. Auto variables can be only accessed within the block/function they have been declared and not outside them. In C, all variables in functions are local by default. That’s why the keyword auto is hardly ever used.They are assigned a garbage value by default whenever they are declared.
Example:

void some_function() { 
      auto int count = 0;
      int count2 = 0;    //auto by default
     }

The two variables “count” and “count2” have automatic storage duration. In other words, they will exist until the program execution reaches the closing bracket of the block where they were defined. In this case they will exist until we reach the end of the function.While we are on the subject, let’s take another look at “block lifetime” variable:

int main() {
            auto int number = 5;
             {
               auto int number = 20;
               printf("inner number: %d", number);
             }
                printf("");
                printf("outer number: %d", number);
                return 0;
    }  

Output

inner number: 20
outer number: 5

Extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block/file where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well.

So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere.

It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only.

The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program.
Few examples:

    extern int var; 
   int main(void) 
     {  
     return 0; 
    } 

Analysis: This program is compiled successfully. Here var is declared only. Notice var is never used so no problems.

   extern int var;
   int main(void)  
       { 
          var = 10; 
           return 0;
       } 

Analysis: This program throws error in compilation. Because var is declared but not defined anywhere. Essentially, the var isn’t allocated any memory. And the program is trying to change the value to 10 of a variable that doesn’t exist at all.

 extern int var = 0; 
       int main(void) { 
           var = 10;
       return 0;
     }

If an extern variable is only declared and an initializer is also provided with that declaration, then the memory for that variable will be allocated i.e. that variable will be considered as defined. Therefore, as per the C standard, this program will compile successfully and work.

 #include "somefile.h" 
  extern int var; 
   int main(void)
           { var = 10;
               return 0;
           } 

Analysis: Supposing that somefile.h has the definition of var. This program will be compiled successfully.

Register: This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only.

Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.

To specify the storage class for a variable, the following syntax is to be followed:

register char b = 'G';

Static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope.

So we can say that they are initialized only once at compile time and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined.

Inside a function it makes the variable to retain its value between multiple function calls Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.

  int fun() {
         static int count = 0;
         count++;
          return count;
              }
                
 int main() {
          printf("%d ", fun());
          printf("%d ", fun());
          return 0;
           }

Output:

1 2

Q3.What is Volatile keyword in C?

Volatile qualifier tells the compiler explicitly that a variable’s value may be changed at any time by some external sources (from outside the program).Example: volatile int date;

When we declare a variable as volatile, the compiler will examine the value of the variable each time it is encountered to see whether any external alteration has changed the value.

Q4. What is the difference between Definition and Declaration in C?

Declaration: When you declare a variable, a function, or even a class all you are doing is saying: there is something with this name, and it has this type. The compiler can then handle most (but not all) uses of that name without needing the full definition of that name. Declaring a value–without defining it–allows you to write code that the compiler can understand without having to put all of the details.Example of declaration:extern int bar;
double f(int, double);

Now the use of extern is creating a declaration of a variable but NOT defining it,it is saying that the storage for the variable is somewhere else.

Definition:Definition declares a variable and causes the storage to be allocated. It means you are telling the compiler where to create the storage for that variable

     int x;
       int main()
                {
             x = 3;
      }          

Q5. What is scope of a variable?

The scope is the region in any program where the defined variable has its existence. It cannot be accessed beyond this scope.The three places where the variables can be declared are:

  1. Local variables which are inside a function or a block.
  2. Global variables which are outside all the functions.
  3. Formal parameters which are defined in the function parameters.

Local variables

  • Local variables are the ones that are declared inside the function or the block.
  • Only the statements which are inside this block are able to access these variables.
  • They are not known to the functions outside.

Example:

 void main() {
           int x,y; //local variables
            int c;
         }     

Default value of local variable: garbage

Global variables

  • The variables which are defined outside a function or block generally on top of the program are known as Global variables.
  • The value of the variable is held throughout the program.
  • They can be accessed anywhere in the program and in any function.

Example: Declaration of global variable

      int n; //global variable
           int main() {
              //n is accessible inside main
               }

Default value of global variable : 0

Formal Parameters: Formal parameters, are treated as local variables with-in a function and they take precedence over global variables.Following is an example–

       /* global variable declaration */
             int a = 20;
             int main () {
          /* local variable declaration in main function */
                    int a = 10;
                    int b = 20;
                    int c = 0;
                
                    printf ("value of a in main() = %d ",  a);
                    c = sum( a, b);
                
                    printf ("value of c in main() = %d ",  c);
                    return 0;
                }
                
      /* function to add two integers */
                int sum(int a, int b) {
                    printf ("value of a in sum() = %d ",  a);
                    printf ("value of b in sum() = %d ",  b);
                    return a + b;
                }

Output

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Q6. Which is better? If-Else or Switch?

Lets discuss advantages of switch over if-else and vice-versa

  • The variable expression is also not allowed in cases. For instance:

case a + 3:  is not correct in switch, but it can be used in if-else

  • You cannot use similar expressions for multiple cases. For instance below switch statement in c is illegal:
 Switch (exp)
                    {
          case 3:
              Statement 1
                    
          case 1+2:
            Statement 2
        }

In above example, both case expressions have the same resultant value 3

  • A switch statement works much faster than equivalent if else ladder”

When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. Therefore, if we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.

  • Clarity in readability: A switch looks much cleaner when you have to combine cases. Ifs are quite vulnerable to errors too. Missing an else statement can land you up in havoc. Adding/removing labels is also easier with a switch and makes your code significantly easier to change and maintain.

Q7. What is a conditional operator in C?

(number >= 1000) ? a + b + c : d + e + f;

Here in the above example, if (number >= 1000) is TRUE then result of whole expression is expression2 which is (a + b + c) and expression3 (d + e + f) is not evaluated at all. But if (number >= 1000) evaluates to FALSE then result of the entire expression is expression3 which is (d + e + f) and expression2 isn’t evaluated at all.Basically, conditional operator is same as if-else construct. We can rewrite the above conditional expression as:

                    if (expression1)
                        expression2;
                    else
                        expression3;
                    

Advantages of conditional operator over if-else construct:

Then what is the difference between conditional expression and if-else statement? Firstly, the conditional expression is little bit more compact than if-else construct. For example:

      // b written twice using if-else 
                 if (ch == 'A') {
                        b = 5;
                    }
                  else {
                        b = ch + 5;
                    }
     // b written once using conditional operator
                 b = (ch == 'A') ? 5 : ch + 5;

Q8. What is the difference between break and continue in C?

break Statement

The break statement terminates the loop (for, while and do…while loop) immediately when it is encountered. The break statement is used with decision-making statement such as if…else.Syntax of break statement

break;

How does break statement work?
Example 1: break statement

  /* Program to calculate the sum of maximum of 10 numbers
           Calculates sum only until user enters positive number */
           int main() {
                    int i;
                    double number, sum = 0.0;
             for(i=1; i <= 10; ++i) {
                     printf("Enter a n%d: ",i);
                    scanf("%lf",&number);
                   // If user enters negative number, loop is terminated
              if(number < 0.0) { 
                    break; }
            sum += number; // sum = sum + number;
                    }
             printf("Sum = %.2lf",sum);
                    return 0;
         }

Output

Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3

Sum = 10.30

This program calculates the sum of the maximum of 10 numbers. It’s because, when the user enters negative number, the break statement is executed and loop is terminated.In C programming, break statement is also used with switch…case statement. continue Statement

The continue statement skips some statements inside the loop. The continue statement is used with decision making statement such as if…else.

Syntax of continue Statement

continue; 

How continue statement works?

Example 2: continue statement

  /* Program to calculate sum of maximum of 10 numbers
        Negative numbers are skipped from calculation */
           int main() {
             int i;
           double number, sum = 0.0;
              for(i=1; i <= 10; ++i) {
                    printf("Enter a n%d: ",i);
                    scanf("%lf",&number);
               // If user enters negative number, loop is terminated
               if(number < 0.0) {
                    continue;
                    }
                    sum += number; // sum = sum + number;
            }
           printf("Sum = %.2lf",sum);
          return 0;
   }

 Output

Enter a n1: 1.1
Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12

Sum = 59.70

In the program, when the user enters positive number, the sum is calculated using sum += number; statement.

When the user enters negative number, the continue statement is executed and skips the negative number from calculation.

Q9. What is a function in C?

A function is a block of code that performs a specific task.

Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and color from the user. You can create two functions to solve this problem:

  • create a circle function
  • color function

Dividing the complex problem into small components makes program easy to understand and use.

Types of functions in C programming:

Depending on whether a function is defined by the user or already included in C compilers, there are two types of functions in C programming:

  • Standard library functions
  • User-defined functions

Standard library functions :
The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc.

These functions are defined in the header file. When you include the header file, these functions are available for use.

Q10. Difference between Pass by value and Pass by reference in C functions?

Pass by value: Passing an argument by value to a function means that the function will have its own copy of the argument, namely the value of the argument is copied from the caller to the callee. It turns out that modifying that copy will not modify the original argument.

Pass by reference: Conversely, address of the actual parameter is passed to the function , a copy of the address of the actual parameter is stored when passing by reference, the parameter inside the function refers to the same object that was passed in. It turns out that any changes operated on the object from inside the function will be seen outside as well.

main() {
            
  int i = 10, j = 20;
                
            swapThemByVal(i, j);
            cout << i << "  " << j << endl;     // displays 10  20
                
             swapThemByRef(&i, &j);              //address of I and j is passed
              cout << i << "  " << j << endl;     // displays 20  10
                }
                
  void swapThemByVal(int num1, int num2) {    //Pass by Value
             int temp = num1;
             num1 = num2;
            num2 = temp;
                }
                
  void swapThemByRef(int  *num1, int *num2) {  //Pass by reference
            int temp = num1;
             num1 = num2;
            num2 = temp;
                }

Q11. What is Recursion in C?

When a called function in turn calls another function a process of chaining occurs.Recursion is a special case of this process, where a function calls itself.

Example of recursion is the evaluation of factorials of given number. The factorial of a number is expressed as a series of repetitive multiplications as shown below :Factorial of n = n(n-1)(n-2)………..1

Factorial can be calculated using recursion as follows:

                factorial(int n) {
                    int fact;
                
                    if(n == 1) {
                        return 1;
                    } else {
                        fact = n*factorial(n-1);
                    }
                
                    return (fact);
                }

Q12. Recursion vs. Iteration, Which is better?

Here are some of the points on recursion and iteration

  • If a recursive method is called with a base case, the method returns a result. If a method is called with a more complex problem, the method divides the problem into two or more conceptual pieces: a piece that the method knows how to do and a slightly smaller version of the original problem. Because this new problem looks like the original problem, the method launches a recursive call to work on the smaller problem.
  • For recursion to terminate, each time the recursion method calls itself with a slightly simpler version of the original problem, the sequence of smaller and smaller problems must converge on the base case. When the method recognizes the base case, the result is returned to the previous method call and a sequence of returns ensures all the way up the line until the original call of the method eventually returns the final result.
  • Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated method calls.
  • Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails; recursion terminates when a base case is recognized.

Q13. What are the differences between structure in C vs structure in C++?

In C++, struct and class are exactly the same things, except for that struct defaults to public visibility and class defaults to private visibility.Some important differences between the C and C++ structures:

  • Member functions inside structure: Structures in C cannot have member functions inside structure but Structures in C++ can have member functions along with data members.
  • Direct Initialization: We cannot directly initialize structure data members in C but we can do it in C++.
// C program to demonstrate that direct member initialization is not possible in C           
     struct Record {
                    int x = 7;
                };
          int main() {
          struct Record s;
          printf("%d", s.x);
          return 0; 
   }

Output:

  Compiler Error

                    6:8: error: expected ':', ',', ';', '}' or
                 '__attribute__' before '=' token
                 int x = 7;
                
                        ^
                In function 'main': 

Using struct keyword:

In C, we need to use struct to declare a struct variable. In C++, struct is not necessary. For example, let there be a structure for Record. In C, we must use “struct Record” for Record variables. In C++, we need not use struct and using ‘Record‘only would work. Static Members: C structures cannot have static members but is allowed in C++.C program with structure static member

       struct Record {
                static int x;
                };
                
       int main() {
                return 0;
                }

Output:

                /* 6:5: error: expected specifier-qualifier-list
                before 'static'
                static int x;
                    ^*/
                

This will generate an error in C but no error in C++.

sizeof operator: This operator will generate 0 for an empty structure in C whereas 1 for an empty structure in C++.

C program to illustrate empty structure

           //empty structure
                struct Record {
                };
                
                int main() {
                    struct Record s;
                    printf("%d",sizeof(s));
                    return 0; 
          }
                

Output in C:
0

Output in C++:
1

Data Hiding:C structures do not allow the concept of Data hiding but is permitted in C++ as C++ is an object-oriented language whereas C is not.

Access Modifiers: C structures does not have access modifiers as these modifiers are not supported by the language. C++ structures can have this concept as it is inbuilt in the language.

Q14. Discuss Structure vs. union in C.

Here are the difference between Structure and Union in C:

structureunion
Keyword struct defines a structure.Keyword union defines a union.
Example structure declaration: struct s_tag { int ival; float fval; char *cptr; }s;Example union declaration: union u_tag { int ival; float fval; char *cptr; }u;
Within a structure all members get memory allocated and members have addresses that increase as the declarators are read left-to-right. That is, the members of a structure all begin at different offsets from the base of the structure. The offset of a particular member corresponds to the order of its declaration; the first member is at offset 0. The total size of a structure is the sum of the size of all the members or more because of appropriate alignment.For a union, compiler allocates the memory for the largest of all members and in a union, all members have offset zero from the base, the container is big enough to hold the WIDEST member, and the alignment is appropriate for all of the types in the union. When the storage space allocated to the union contains a smaller member, the extra space between the end of the smaller member and the end of the allocated memory remains unaltered.
Within a structure all members get memory allocated; therefore any member can be retrieved at any time.While retrieving data from a union the type that is being retrieved must be the type most recently stored. It is the programmer’s responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.
One or more members of a structure can be initialized at once.A union may only be initialized with a value of the type of its first member; thus union u described above (during example declaration) can only be initialized with an integer value.

Q15 .What are Pointers in C?

pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address.

The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer’s base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.

Take a look at some of the valid pointer declarations:

int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *ch     /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

Q16. Void pointer vs. Null pointer in C

Void pointer: It is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void refers to the type. Basically the type of data that it points to is can be any. If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any value. void pointers cannot be dereferenced. It can however be done using typecasting the void pointer Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.

Example:

          int main() {
                    int x = 4;
                    float y = 5.5;
                
                    void *ptr;  //A void pointer
                    ptr = &x;
                
                // (int*)ptr - does type casting of void
                // *((int*)ptr) dereferences the typecasted
                // void pointer variable.
                
                    printf("Integer variable is = %d", *( (int*) ptr) );
                
                // void pointer is now float
                    ptr = &y;
                    printf(" Float variable is= %f", *( (float*) ptr) );
                    return 0;
           } 

Output:

Integer variable is = 4
Float variable is= 5.500000

NULL Pointer:NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL.

A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.

    int main() {
                  int *ptr = NULL;    // Null Pointer
                  printf("The value of ptr is %u", ptr);
                  return 0;
             }

Q17. What are the Similarities and Differences in Arrays vs. Pointers in C?

Similarities between arrays and pointers

1)Array name gives the address of the first element of an array.

int main() {
         int arr[] = {10, 20, 30, 40, 50, 60};
         int *ptr = arr;  // Assigns address of array to ptr
        printf("Value of first element is %d", *ptr);
         return 0;
             }

Output:

Value of first element is 10

2)Array members are accessed using pointer arithmetic.

Compiler uses pointer arithmetic to access array element. For example, an expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr.

  int main() {
              int arr[] = {10, 20, 30, 40, 50, 60};
              int *ptr = arr;
              printf("arr[2] = %d ", arr[2]);
              printf("*(arr + 2) = %d ", *(arr + 2));
              printf("ptr[2] = %d ", ptr[2]);
              printf("*(ptr + 2) = %d ", *(ptr + 2));
              return 0;
 }

Output: 

arr[2] = 30 *(arr + 2) = 30 ptr[2] = 30 *(ptr + 2) = 30 

3) Array parameters are always passed as pointers, even when we use square brackets.

     int fun(int ptr[]) {
            int x = 10;
             printf("sizeof(ptr) = %d ", sizeof(ptr));  // size of a pointer is printed
                
              ptr = &x; // This allowed because ptr is a pointer, not array
                    printf("*ptr = %d ", *ptr);
                
               return 0;
        }
    int main() {
               int arr[] = {10, 20, 30, 40, 50, 60};
               fun(arr);
               return 0;
                }

Output

sizeof(ptr) = 4
*ptr = 10

Q18. Difference between arrays and pointers ?

1)Behavior of sizeof operator

Program to show that array and pointers are different

 int main() {
                 int arr[] = {10, 20, 30, 40, 50, 60};
                    int *ptr = arr;
                  // sizof(int) * (number of element in arr[]) is printed
                    printf("Size of arr[] %d ", sizeof(arr));
                 // sizeof a pointer is printed which is same for all type of pointers (char *, void *, etc)
                    printf("Size of ptr %d", sizeof(ptr));
                   return 0;
        }       

Output:

Size of arr[] 24
Size of ptr 4
2) Assigning any address to an array variable is not allowed

Program to show that array and pointers are different

  int main() {
                 int arr[] = {10, 20}, x = 10;
                 int *ptr = &x; // This is fine
                  arr = &x;  // Compiler Error
                  return 0;
          }

Q19. Difference between Malloc and Calloc in C.

The name malloc and calloc() are library functions that allocate memory dynamically. It means that memory is allocated during runtime(execution of the program) from heap segment.

  1. malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If we try to acess the content of memory block then we’ll get garbage values.

Syntax of malloc:

void * malloc( size_t size );
  1. calloc() allocates the memory and also initializes the allocates memory block to zero. If we try to access the content of these blocks then we’ll get 0.

Syntax of calloc:

void * calloc( size_t num, size_t size );
  • Number of arguments: Unlike malloc(), calloc() takes two arguments:
    1) Number of blocks to be allocated.
    2) Size of each block.
  • Return Value: After successfull allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL value is returned which indicates the failure of allocation.

Q20. What is the use of realloc?

If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().

Syntax of realloc()

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.
Example:

         int main() {
               int *ptr, i , n1, n2;
               printf("Enter size of array: ");
                    scanf("%d", &n1);
               ptr = (int*) malloc(n1 * sizeof(int));
                
               printf("Address of previously allocated memory: ");
                    for(i = 0; i < n1; ++i)
                    printf("%u	",ptr + i);
                
               printf("Enter new size of array: ");
                    scanf("%d", &n2);
                
               ptr = realloc(ptr, n2); 
                
                    for(i = 0; i < n2; ++i)
                    printf("%u	", ptr + i);
                    return 0;
            }

Q21. When is free keyword used in C?

Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on its own. You must explicitly use free() to release the space.

syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

Q22. How to dynamically allocate 1D and 2D array in C?

1D array can be dynamically allocated as per following

Syntax: 

data_type *arr = (data_type *)malloc(size_of_array * sizeof(data_type));


Example:

 int * arr = (int )malloc(n*sizeof(int));  //n is count of array elements for which we want to allocate memory

Note : After memory allocation , malloc returns void*, which is a generic pointer that can point to any type of data.

Hence it has to be explicit to the data type we want it to point to.2D array can be dynamically allocated as per following ways:

1) Using a single pointer:

A simple way is to allocate the memory block of size r*c and access elements using simple pointer arithmetic.

  int main() {
             int r = 3, c = 4;
             int *arr = (int *)malloc(r * c * sizeof(int));
             int i, j, count = 0;
                for (i = 0; i <  r; i++) {
                       for (j = 0; j < c; j++) {
                            *(arr + i*c + j) = ++count;
                          }
                      }
                  for (i = 0; i <  r; i++) {
                      for (j = 0; j < c; j++) {
                          printf("%d ", *(arr + i*c + j));
                        }
                  }
                return 0;  
                }

Output:

1 2 3 4 5 6 7 8 9 10 11 12

2) Using an array of pointers

We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.

 int main() {
             int r = 3, c = 4, i, j, count;
              int *arr[r];
              for (i=0; i<r; i++)
                    arr[i] = (int *)malloc(c * sizeof(int));
                   // Note that arr[i][j] is same as *(*(arr+i)+j)
                    count = 0;
                  for (i = 0; i <  r; i++) {
                        for (j = 0; j < c; j++) {
                            arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count
                        }
                    }
                 for (i = 0; i <  r; i++) {
                        for (j = 0; j < c; j++) {
                            printf("%d ", arr[i][j]);
                        }
                    }
                
                    return 0;
                }

Output:

1 2 3 4 5 6 7 8 9 10 11 12

3) Using pointer to a pointer

We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.

int main() {
          int r = 3, c = 4, i, j, count;
          int **arr = (int **)malloc(r * sizeof(int *));
                 for (i=0; i<r; i++)
                        arr[i] = (int *)malloc(c * sizeof(int));
                 // Note that arr[i][j] is same as *(*(arr+i)+j)
                   count = 0;
                  for (i = 0; i <  r; i++) {
                        for (j = 0; j < c; j++) {
                            arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
                   }
             }
                
             for (i = 0; i <  r; i++) {
                        for (j = 0; j < c; j++) {
                            printf("%d ", arr[i][j]); 
                        }
                    }
             return 0;
          }

Output:

1 2 3 4 5 6 7 8 9 10 11 12

4) Using double pointer and one malloc call for all rows


int main() 
      {    int r=3, c=4; 
            int **arr; 
            int count = 0,i,j; 
            arr  = (int **)malloc(sizeof(int *) * r); 
            arr[0] = (int *)malloc(sizeof(int) * c * r); 
           for(i = 0; i < r; i++) 
                  arr[i] = (*arr + c * i); 
                   for (i = 0; i < r; i++) { 
                         for (j = 0; j < c; j++) 
                             { arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
               } } 
              for (i = 0; i <  r; i++) 
                               { 
             for (j = 0; j < c; j++) 
             { 
                    printf("%d ", arr[i][j]); 
                    }
            }
       return 0;
    }

Hope this article on C Interview Questions is helpful to you. Feel free to comment for suggestions to improve and ask a question!

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.