当前位置: 代码迷 >> 综合 >> C语言 结构体成员定义及使用问题
  详细解决方案

C语言 结构体成员定义及使用问题

热度:47   发布时间:2024-01-20 10:04:58.0

程序如下:

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

struct test
{
  short a;
  short b;
};

void foo(int *out)
{
     int tmp = 1111111;
     *out = tmp;
     return;
}

int main()
{
    struct test all;
    all.a = 0;
    all.b = 20;
    foo(&(all.a));
    printf("\r\n all.a=%d\r\n", all.a);
    printf("\r\n all.b=%d\r\n", all.b);
    return 0;
}

 

foo(&(all.a));的调用是错误的。

原因在于foo()  函数中的参数指针为int类型,占4字节。而这里调用时给他的只是2字节。

在强制类型转换后,导致test结构体中的b也会被赋值。因为short a和short b加起来才4字节。所以在内存中,b会被赋值,且为a越界的那部分的值。

 

对于OS会提示Alignment Trap问题,不一定说是内存对齐问题,而是内存使用的问题。

 

说明,如果定义临时变量使用强制类型转换,就不会存在这样的问题。

如:

short a =10;

int b = (int)a;

这样的用法是没有问题的。

对于在结构体中连续的内存在做指针类型进行转换的,就需要特别小心。

 


 

  相关解决方案