加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C结构中char *和char []的差异

发布时间:2020-12-16 09:52:54 所属栏目:百科 来源:网络整理
导读:当我想在C结构中存储动态数据数组时,有两种方法可以编写它: typedef struct { int row; int col; char* data;} item1; 要么 typedef struct { int row; int col; char data[];} item2; 他们俩都会工作.但他们在我的64位Mac OSX上有一些差异,使用gcc Apple L
当我想在C结构中存储动态数据数组时,有两种方法可以编写它:

typedef struct {
   int row;
   int col;
   char* data;
} item1;

要么

typedef struct {
   int row;
   int col;
   char data[];
} item2;

他们俩都会工作.但他们在我的64位Mac OSX上有一些差异,使用gcc Apple LLVM 5.1版(clang-503.0.38):

sizeof(item1) is 16
      sizeof(item2) is 8

为什么有区别?而且,这两种实现还有什么不同?

完整的测试代码是:

#include <stdio.h>

typedef struct {
  int row;
  int col;
  char* data;
} item1;


typedef struct {
  int row;
  int col;
  char data[];
} item2;


int main() {
  printf("%d %dn",sizeof(item1),sizeof(item2));
  return 0;
}

输出是:

16 8

解决方法

指针大小为 machine specific(无论是32位还是64位).结果在32位机器上分别为12和8字节.对于64位机器,答案是16和8字节.
请参阅说明

typedef struct {
   int row;         // 4 bytes
   int col;         // 4 bytes
   char* data;      // 4/8 bytes on 32/64-bit machine
}item1 ;

32/64位计算机上的总大小= 12/16字节.

typedef struct {
   int row;         // 4 bytes
   int col;         // 4 bytes
   char data[];     // 0 bytes --> Flexible array 
}item2 ;

总大小= 8个字节.

为什么灵活数组的大小为0?

C11:6.7.2.1(第18页)

[…] In particular,the size of the structure is as if the flexible array member were omitted […]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读