C语言自定义结构强制转换,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 #include 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<

#include 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

*/

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