我有返回一個指針陣列的功能,我想在陣列中打印的每個值印刷值從函數(C++)返回
當運行它,它打印
int* merge_sort(int arr[], int size) {
if (size <= 1) {
return &arr[0];
}
int size1 = size/2;
int arr1[size1];
for (int i = 0; i < size1; i++) {
arr1[i] = arr[i];
}
int size2 = size-size1;
int arr2[size2];
for (int i = 0; i < (size2); i++) {
arr2[i] = arr[i+size1];
}
int p1 = 0;
int p2 = 0;
int sorted[size];
while (p1 < size1 && p2 < size2) {
if (arr1[p1] < arr2[p2]) {
sorted[p1+p2] = arr1[p1];
p1++;
} else {
sorted[p1+p2] = arr2[p2];
p2++;
}
}
while (p1 < size1) {
sorted[p1+p2] = arr1[p1];
p1++;
}
while (p2 < size2) {
sorted[p1+p2] = arr2[p2];
p2++;
}
cerr << "sorted: ";
for (int& i : sorted) {
cerr << i << ",";
}
cerr << endl;
return &sorted[0];
}
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
int horses[N];
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) {
int Pi;
cin >> Pi; cin.ignore();
horses[i] = Pi;
}
int *sorted = merge_sort(horses, N);
cerr << "~ " << sorted[0] << " " << sorted[1] << " " << sorted[2] << endl;
//cerr << "~~ " << sorted << " " << *sorted << " " << endl;
cerr << "^ " << *(sorted + 0) << endl;
cerr << "^ " << *(sorted + 1) << endl;
cerr << "^ " << *(sorted + 2) << endl;
for (int i = 0; i < N; i++) {
//cerr << "i " << i << endl;
// cerr << "SORTED?? " << sorted[i] << endl;
cerr << "value: " << *(sorted + i) << " ";
//cerr << "*** " << *(sorted) + i << endl;
}
cerr << endl;
}
當運行它,它打印
排序:5,8,9, 〜5 8 9 ^ -5728 ^ 942815029 ^ 6297320 值:959592096值:0值:-157570874
爲什麼我的循環不打印值「5,8,9」?我該如何解決這個問題呢?
(編輯成更細。而且,我知道我的歸併排序是錯誤的,但我只是想獲得它返回的東西我現在^可以使用。^)
能否請您嘗試創建一個[最小,完整,可驗證的示例](HTTP://計算器.com/help/mcve)並向我們展示? –
如果array是你傳遞給函數的指針,那你爲什麼要返回它? – PRP
@PRP,好的一點是,OP已經擁有指向「sort」的指針,指針本身不會改變。 – SingerOfTheFall