C中char数据类型和char数组的大小

2021年4月15日19:02:37 发表评论 695 次浏览

给定一个char变量和一个char数组, 任务是编写一个程序来查找C中此char变量和char数组的大小。

例子:

Input: ch = 'G', arr[] = {'G', 'F', 'G'}
Output: 
Size of char datatype is: 1 byte
Size of char array is: 3 byte

Input: ch = 'G', arr[] = {'G', 'F'}
Output: 
Size of char datatype is: 1 byte
Size of char array is: 2 byte

方法:

在下面的程序中, 找到char变量和char数组的大小:

  • 首先, 在charType中定义char变量, 在arr中定义char数组。
  • 然后, 使用sizeof()运算符.
  • 然后, 将整个数组的大小除以第一个变量的大小, 即可找到char数组的大小。

下面是C程序, 用于查找char变量和char数组的大小:

//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;
}

输出如下:

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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: