• Register
1,240 points
10 7 4

The problem given to us is “Get the length of the char array in C++”. Basically we have given a char variable and char array. We have to find the size of the char variable and char array. For your convenience see this example if you didn’t understand the question till now.

We’ll discuss the approach for writing the program for it and we’ll also write the program.

 

Approach

I am breaking down the approach in steps. Since it will be easy to understand and we can follow and find the error if we made it.

  • First of all, we have to define the variable of type char and the char array.

  • Then we will find the size of the variable char by using the sizeof() operator.

  • After that, we will find the size of the char array by dividing the size of the complete array by the size of the first variable.

Program

// C program to find the size of 
// char data type and char array 
  
#include <stdio.h> 
  
int main() 
{ 
  
    char charType = 'G'; 
    char arr[] = { 'G', 'F', 'G' }; 
  
    // Calculate and Print 
    // the size of charType 
    printf("Size of char datatype is: %ld byte\n", 
           sizeof(charType)); 
  
    // Calculate the size of char array 
    size_t size = sizeof(arr) / sizeof(arr[0]); 
  
    // Print the size of char array 
    printf("Size of char array is: %ld byte", 
           size); 
  
    return 0; 
} 

Output

Size of char datatype is: 1 byte
Size of char array is: 3 byte

If you find any difficulties and any doubt then feel free to ask in the comment section. I’ll love to help you ASAP.