结构体的内存存放是不是与编译器有关?

吾非善类 2021-02-25 06:28:02
主程序如下
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 #define _int64 long long
5
6 typedef struct Data_c{
7 char str[12];
8 _int64 a;
9 int b;
10 } Data;
11
12 int main(){
13 Data* dataP=(Data*)malloc(sizeof(Data));
14 printf("dataP address size is %lld\n",(dataP));
15 printf("dataP->a address size is %lld\n",&(dataP->a));
16 printf("subl dataP->a , dataP is %lld\n",(_int64)&(dataP->a)-(_int64)dataP);
17 *((_int64*)((_int64)dataP+16))=56;
18 printf("dataP->a is %lld\n",dataP->a);
19 return 0;
20 }
然后呢输出结果如下
$ ./a
dataP address size is 34359739296
dataP->a address size is 34359739312
subl dataP->a , dataP is 16
dataP->a is 56

按说,正确的应该是subl dataP->a,dataP 应该是12,为什么会变成了16呢?因为编译器原因吗?
我的编译器是windows下的cygwin64Terminal的gcc

$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/10/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with: /mnt/share/cygpkgs/gcc/gcc.x86_64/src/gcc-10.2.0/configure --srcdir=/mnt/share/cygpkgs/gcc/gcc.x86_64/src/gcc-10.2.0 --prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --with-gcc-major-version-only --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-tune=generic --enable-languages=c,c++,fortran,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --enable-libquadmath --enable-libquadmath-support --disable-libssp --enable-libada --disable-symvers --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id --with-default-libstdcxx-abi=gcc4-compatible --enable-libstdcxx-filesystem-ts
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.2.0 (GCC)
...全文
97 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
吾非善类 2021-02-25
  • 打赏
  • 举报
回复
谢谢各位大佬,明白了
自信男孩 2021-02-25
  • 打赏
  • 举报
回复
打印地址,建议用%p,不建议用%lld,因为16进制看地址比较方便,第二个是%d是有符号数,而地址是无符号类型的数据。
xian0-666 2021-02-25
  • 打赏
  • 举报
回复
结构体对齐并不是简单的相加,具体规范百度
真相重于对错 2021-02-25
  • 打赏
  • 举报
回复
内存对齐啊,64位应该是按8字节对齐的 vs的话可以用#pragma pack (4) ,修改它 gcc 这个语句是否管用,我没试过。 gcc好像可以用__attribute__ ((aligned (n))),我没有gcc,没法试

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧