[英]C++ Passing a Dynamically Created Array with Pointers
希望獲得一些C ++的幫助-我對這個話題很陌生。 我試圖根據用戶輸入的指針動態創建一個數組,然后將該數組傳遞給函數。 但是指針(以及數組)傳遞感覺有點不對勁,因為沒有發生解除引用的情況。
在傳遞過程中/傳遞之后,我們是否只將指針視為任何正常聲明並傳遞的數組,而無需取消引用(*)任何東西? 還是我應用不正確?
偽代碼如下:
#include<iostream>
using namespace std;
void arrayFunc(int [], int); // << Note no indication of pointer pass
int main()
{
int *arrayPtr = 0; // Array pointer
int arrayElem = 0; // Number of elements in array
cout << "\nPlease enter the number of elements: ";
cin >> arrayElem;
arrayPtr = new int[arrayElem]; // Dynamically create the new array
arrayFunc(arrayPtr, arrayElem); // << Note no dereferencing or other indication of pointer
return 0;
}
void arrayFunc(int array[], int arrayElem) // << Same here - now it's just a plain old array
{
// All the functiony-bits go here, referencing array without the need to dereference
}
[編輯]上面的代碼有效時,以下內容包括以下討論中確定的修復程序:
#include<iostream>
using namespace std;
void arrayFunc(int*, int); // Changed to pointer pass instead of []
int main()
{
int *arrayPtr = 0; // Array pointer
int arrayElem = 0; // Number of elements in array
cout << "\nPlease enter the number of elements: ";
cin >> arrayElem;
arrayPtr = new int[arrayElem]; // Dynamically create the new array
arrayFunc(arrayPtr, arrayElem);
return 0;
}
void arrayFunc(int* array, int arrayElem) // Passing a pointer now instead of []
{
// All the functiony-bits go here, referencing array without the need to dereference
}
您的嘗試是正確的。 您正在按值傳遞數組指針。 然后,您可以在arrayFunc
正常取消引用
您應該在函數中傳遞指針,因為它可以准確描述情況,即傳遞動態分配的內存。 arrayPtr
本質上是指向數組第一個元素的指針。 因此,您不必擔心取消引用它。
將功能簽名更改為:
void arrayFunc(int*, int);
C的設計是假裝一個指針和一個數組幾乎是同一回事。 因此,許多簡單的用法都比較容易。 但是,當您考慮指向數組的指針時,該概念變得更加混亂。 感覺這不應該與指向該數組第一個元素的指針相同,但是在分配內存和使用指針的通用方法中,指向數組的指針實際上只是指向該數組的第一個元素的指針數組。
我發現最好將“指向數組的第一個元素的指針”視為C中*的正常含義。指向標量對象的特殊情況是將標量有效地視為數組的第一個(也是唯一的)元素長度為1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.