---
title: "sizeof和数组类型"
author: "splayx"
date: "2014-02-22T19:23:54Z"
tags: []
categories: ["编程语言"]
slug: "sizeof"
draft: false
lastmod: "2014-02-22T19:23:54Z"
id: 2020550
url: "https://splayx.iteye.com/blog/2020550"
---

sizeof（类型）可以得到一个类型的大小，

比较容易搞错的是把数组类型看成指针类型，见下面的代码：

 

```
#include <stdio.h>

// error: cannot convert
// ‘char*’ to ‘int*’ for argument ‘1’ to ‘void fun(int*)’
// 可见a被看成指针，而不是一个数组类型
// 所以这里怎么都是打印出指针类型的大小
// void fun(int a[10]) {
//    printf("%d\n", sizeof(a));
// }

void fun(char a[10]) {
    printf("%d\n", sizeof(a));
}

// run in 64bit machine

int main() {
    char *a = "1234567890";
    char b[100] = "1234567890";
    char c[10] = "123";

    // incompatible types in assignment of ‘char [100]’ to ‘char [10]’
    // array type has 2 attr: type(e.g. char), size(e.g. 100)
    // c = b;

    char d[100];
    // error: ISO C++ forbids assignment of arrays
    // d = b;

    // print 100
    // 打印出数组类型(char [100])的大小
    printf("%d\n", sizeof(b));

    // print 8
    fun(a);

    // print 8
    fun(b);

    return 0;
}
```