C语言中数据类型的长度

面试中C里面int长度经常会被问到,下面总结一下作为资料:

首先看看一般规定:

标准c规定,int长度等于机器字长,short的表示范围不能大于int的表示范围,long的表示范围不能小于int的表示范围。在32为平台上(所谓32位平台是指通用寄存器的数据宽度是32)编写代码,short一般是16位,而long和int是32位。而在16位平台,int 和 short 一般都是16位,而long是32位。

下面写代码实际测试一下:

#include <stdio.h>
#include <stdlib.h>

int main(){
 printf("len int = %d
 ", sizeof(int));
 printf("len short = %d
 ", sizeof(short));
 printf("len long = %d
 ", sizeof(long));
 printf("len long long = %d
 ", sizeof(long long));
 printf("len float = %d
 ", sizeof(float));
 printf("len double = %d
 ", sizeof(double));
 char *a= "test";
 char b[] = "test";
 printf("len *a = %d
 ", sizeof(a));
 printf("len b[] = %d
 ", sizeof(b));
 typedef struct Node{
   int value;
   struct Node* next; 
 }Node;
 Node node;
 printf("len struct Node = %d
 ", sizeof(node));
}

输出如下:

 len int = 4
 len short = 2
 len long = 4
 len long long = 8
 len float = 4
 len double = 8
 len *a = 4
 len b[] = 5
 len struct Node = 8

以前一直以为C里面int是16位的,看来现在的机器都是32位的了。

下面区别一下sizeof() 和strlen();

#include <stdlib.h>
#include <string.h>

int main(){
char str[] = "dseww";
char* str1 = "dsewaaa";
int len = strlen(str);
int len1 = strlen(str1);
printf("%d ",sizeof(str));//6
printf("%d ",sizeof(str1));//4
printf("%d ",len);//5
printf("%d ",len1);//7
}



原文地址:https://www.cnblogs.com/McQueen1987/p/4012819.html