C - 对函数内部的 Struct* 数组的副本进行排序
struct numz
{
int num;
};
typedef struct numz_ numz;
int main()
{
int num_elements = 10;
numz* myStruct_a = smalloc(sizeof(int)*num_elements;
for (n = 0; n < num_elements; n++)
myStruct_a->num[n] = n;
funct(myStruct_a);
return 0;
}
numz *funct(numz *myStruct_a)
{
int num_elements = 10;
numz* myStruct_a_cpy = smalloc(sizeof(int)*num_elements;
for (n = 0; n < num_elements; n++)
{
myStruct_a_cpy->num[n] = myStruct_a->num[n];
}
//PSEUDO CODE
//REARRANGE THE ELEMENTS IN myStruct_a_cpy
return myStruct_a_cpy;
}
为什么 myStruct_a_cpy
没有重新排列?
struct numz
{
int num;
};
typedef struct numz_ numz;
int main()
{
int num_elements = 10;
numz* myStruct_a = smalloc(sizeof(int)*num_elements;
for (n = 0; n < num_elements; n++)
myStruct_a->num[n] = n;
funct(myStruct_a);
return 0;
}
numz *funct(numz *myStruct_a)
{
int num_elements = 10;
numz* myStruct_a_cpy = smalloc(sizeof(int)*num_elements;
for (n = 0; n < num_elements; n++)
{
myStruct_a_cpy->num[n] = myStruct_a->num[n];
}
//PSEUDO CODE
//REARRANGE THE ELEMENTS IN myStruct_a_cpy
return myStruct_a_cpy;
}
Why is myStruct_a_cpy
not rearranged?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么要使用
smalloc(sizeof(int)*num_elements)
初始化myStruct_a_cpy
?不应该是sizeof(myStruct)
吗?另外,为什么不直接使用 qsort 呢?
int 比较(const void * a, const void * b)
{
myStruct * struct_a = (myStruct*) a;
myStruct * struct_b = (myStruct*) b;
// 比较两个结构体的内容,
// 如果 a < 返回 -1 b,如果a>1,则为1 b,否则为 0。
}
myStruct *funct(myStruct *myStruct_a)
why are you initializing
myStruct_a_cpy
withsmalloc(sizeof(int)*num_elements)
? shouldn't it besizeof(myStruct)
?Also, why not just use qsort?
int compare(const void * a, const void * b)
{
myStruct * struct_a = (myStruct*) a;
myStruct * struct_b = (myStruct*) b;
// compare the contents of the two structs,
// return -1 if a < b, 1 if a > b, and 0 otherwise.
}
myStruct *funct(myStruct *myStruct_a)