gpt4 book ai didi

c - 类型转换,结构与转换

转载 作者:行者123 更新时间:2023-11-30 16:18:30 25 4
gpt4 key购买 nike

我该如何转换这些Student1和Student2变量并访问其成员
可变的?我在student1和student 2变量中有转换错误。

typedef struct {
int id;
int hw_score[3];
int final;
} Student;

int intComparator(void* p, void* q) {
return ((int)p - (int)q);
}

int idComparator(void *student1, void *student2){

int result;
Student* s1, s2;

s1 = (Student*)student1;
s2 = (Student*)student2;

result = intComparator((void*)(s1->id), (void*)(s2->id));

if (result > 0) {return 1;}
else if (result < 0) {return -1;}
else {return 0;}

}


int main()
{
int result;
Student s1, s2;
s1.id = 8;
s2.id = 10;

result = idComparator((void*)&s1, (void*)&s2);
printf("result: %d\n", result);

return 0;
}


我很难理解void *。

最佳答案

除了该策略过于复杂以至于无法执行简单的减法运算外,您的代码中还存在一些错误:

#include <stdio.h>       // a

typedef struct {
int id;
int hw_score[3];
int final;
} Student;

int intComparator(void* p, void* q) {
return (*(int*)p - *(int*)q); // b
}

int idComparator(void *student1, void *student2){

int result;
Student* s1, *s2; // c

s1 = (Student*)student1;
s2 = (Student*)student2;

result = intComparator(&(s1->id), &(s2->id)); // d

if (result > 0) {return 1;}
else if (result < 0) {return -1;}
else {return 0;}

}


int main()
{
int result;
Student s1, s2;
s1.id = 8;
s2.id = 10;

result = idComparator(&s1, &s2);
printf("result: %d\n", result);

return 0;
}


a)printf需要stdio.h

b)* void需要取消引用的类型: Dereference void pointer

c)s2不是指针: Declaring pointers; asterisk on the left or right of the space between the type and name?

d)您不必强制转换为void,但是该函数需要一个地址: Why type cast a void pointer?

这是 live demo,但再次考虑改进您的设计,使其更清晰,更简单。

关于c - 类型转换,结构与转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com