C - 在函数内部对Struct * Array的副本进行排序

时间:2011-08-16 16:24:04

标签: c arrays struct malloc

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没有重新排列?

1 个答案:

答案 0 :(得分:1)

为什么要使用myStruct_a_cpy初始化smalloc(sizeof(int)*num_elements)?不应该是sizeof(myStruct)吗?

另外,为什么不使用qsort?

int compare(const void * a,const void * b) {       myStruct * struct_a =(myStruct *)a;       myStruct * struct_b =(myStruct *)b;       //比较两个结构的内容,       //如果&lt;返回-1 b,1如果a> b,否则为0。 }

myStruct * funct(myStruct * myStruct_a)

{
    int num_elements = 10;
    myStruct* myStruct_a_cpy = smalloc(sizeof(int)*num_elements);
    for (n = 0; n < num_elements; n++)
    {
        myStruct_a_cpy[n] = myStruct_a[n]
    }
    qsort(myStruct_a_cpy, 10, sizeof(myStruct), compare);
}