2017-09-19 8 views
0

힙 배열을 정렬하는 함수를 작성해야합니다. 이 함수는 배열 복사본을 만들고, 복사본을 정렬하고, 정렬 된 복사본에 대한 포인터를 반환해야합니다. 나는 qsort()을 시도했지만 이상한 결과를 얻는다. 나는 그것이 포인터와 관련이 있지만 여전히 그것을 파악할 수 없다고 확신한다.힙 배열 배열

이 내 코드는 지금까지 있습니다 :

int cmpfunc(const void * a, const void * b) 
{ 
    return (*(int*)a - *(int*)b); 
} 

int sorted_copy(int* list[], size_t s) 
{ 
    int aList[s]; 
    memcpy(aList,list,s); 
    printf("Array was copied successfuly to aList[] array\n\n"); 
    printf("Before sorting the list is: \n"); 

    for(int i = 0; i < s; i++) 
     printf("%d\n", aList[i]); 

    qsort(aList, s, sizeof(int), cmpfunc); 
    printf("After sorting the list is: \n"); 
    for(int i = 0; i < s; i++) 
    { 
     printf("%d\n", aList[i]); 
    } 
    return *aList; 
} 

int main() 
{ 
    int list[10] = {4, 1, 2, 7, 3, 5, 6, 0, 8, 9}; 
    sorted_copy(list,sizeof(list)); 
    return 0; 
} 

하는 I가

Array was copied successfuly to aList[] array 

Before sorting the list is: 
4 
1 
2 
7 
3 
5 
6 
0 
8 
9 
0 
0 
0 
0 
3 
0 
0 
0 
268501009 
32762 
4199840 
0 
-1407817721 
32762 
12846904 
0 
1324151619 
0 
8 
0 
176 
0 
6487584 
0 
4199972 
0 
4200528 
0 
-1434081178 
32762 
After sorting the list is: 
-1434081178 
-1407817721 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
1 
2 
3 
3 
4 
5 
6 
7 
8 
8 
9 
176 
32762 
32762 
32762 
4199840 
4199972 
4200528 
6487584 
12846904 
268501009 
1324151619 

Process returned 0 (0x0) execution time : 0.281 s 
Press any key to continue. 
+1

'int' 배열에 포인터를'int' 배열로 덤핑하는 것은 당신이하려는 일에 좋은 시작이 아닙니다. 또한 어쨌든 실제로 용량을 복사하지 않습니다. 'memcpy'의 세 번째 인수는 * bytes * 크기입니다. 요소 카운트가 아닙니다. 마지막으로 "정렬 된 복사본 반환"에는 추가 in/out 매개 변수, 정적 배열 또는 일부 동적 할당이 포함됩니다. – WhozCraig

+0

[this] (https://ideone.com/m9zdtF)와 같이 수정하면 – BLUEPIXY

+1

funcion closure 후에 삭제하는 로컬 변수의 주소를 반환합니다. – bobra

답변

0

잘 받고 있어요이 출력, sorted_copy()의 두 번째 매개 변수로 전달 된 배열의 요소의 수 있어야합니다 첫 번째 매개 변수가 아니고 sizeof (메모리 바이트의 개체 크기) 32 비트 아키텍처를 사용하고 있는데 여기서 int은 4 바이트이고 너는 40을 e 배열에있는 실제 셀 수는 10이 아닙니다.

int main() 
{ 
    int list[] = {4, 1, 2, 7, 3, 5, 6, 0, 8, 9}; 
    sorted_copy(list, sizeof list/sizeof list[0]); 
    return 0; 
} 

변경

int main() 
{ 
    /* you don't need to specify the number of elements to declare 
    * the array if you are using an initializer that fully populates 
    * the array elements */ 
    int list[10] = {4, 1, 2, 7, 3, 5, 6, 0, 8, 9}; 
    sorted_copy(list,sizeof(list)); /* sizeof gives you the array 
            * size in bytes, not in number 
            * of elements */ 
    return 0; 
} 

당신은 올바른 결과를 얻을 수 있습니다.