C语言结构体类型的强制转换

当所用到的各个层次的成员较多时,我们会定义多个结构体函数,但是在传输过程中我们需要具体的指定哪一个结构体作为传输的数据,又C语言中的结构体并不能直接进行强制类型转换,只有结构体的指针可以进行强制类型转换,因此中间涉及到指针的问题,也就涉及到指向空间地址的问题。
我们定义一个结构体如下:

typedef struct stdudent
{
       char name[20];
       int age;
}student_t;

它的含义如下:

第一种: struct student student_1;   //定义了一个student_1的结构体变量

第二种:student_t student_1            //定义了一个student_1的结构体变量

当我们调用子函数时,可能需要传递参数如下:

void *run(void *play)
struct stdudent *Play = (stdudent_t *)play; //因为void 指针是无类型(假设为void * a ),可以接受任何其他类型的指针,
//所以一搬用于形参来接受参数,但当你要使用这个指针的时候就必须转换为具体的类型。所以进行强制转换。

附上例子说明:

#include <iostream>
#include <algorithm>
using namespace std;
typedef struct student
{
    string dna;
    int count;
}student_t;

int cmp(const void *a,const void *b)
{
    student_t *aa = (student_t *)a;   //强制转换
    student_t *bb = (student_t *)b;
    return aa->count-bb->count;
}

int main()
{
    int n,m;
    char c;
    cin>>n>>m;
    for(int i = 0; i < m; i++)
    {
        cin>>dna[i].dna;
        dna[i].count = 0;
        for(int j = 0; j < n; j++)
        for(int k = j+1; k < n; k++)
        {
            if(dna[i].dna[j]>dna[i].dna[k])
            dna[i].count++;
        }
    }
    qsort(dna,m,sizeof(dna[0]),cmp);
    for(int i = 0; i < m; i++)
    cout<<dna[i].dna<<endl;
    return 0;
}
#include <stdio.h>
struct NodeA {
    int a;
    int b;
};
struct NodeB {
    int c;
    int d;
};

int main(int argc, char *argv[])
{
    struct NodeA a1;
    struct NodeB b1;

    a1.a = 1;
    a1.b = 2;
    b1.c = 3;
    b1.d = 4;

    int *p = &(b1.c);
    printf("%d\n", *p);
    printf("%d\n", ((struct NodeA *) p) -> a);
    printf("%d\n", ((struct NodeA *) p) -> b);
    return 0;
}
/*
输出结果:
3
3
4
*/

一般多线程中(传递参数为结构体时)也会用到该强制转换的情况。具体问题具体分析。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值