[英]should this example not alter the memory address rather than the value at that memory address?
[英]Pointer to Elements of an Array printing the memory address rather than the value of the element
我目前正在為一個類編寫程序,該類需要用戶輸入以從動態數組中添加或刪除數字,然后以升序打印該數組的所有值。
根據我的研究,要獲取要打印的數組中元素的值,我要做的就是確保將取消引用運算符插入指針名稱旁邊。 但是,當按如下方式進行操作時( newArray [i]),我收到一個編譯時錯誤消息 ,即使'new'在函數的開頭被聲明為指針, ' ' 右邊的操作數也必須是一個指針。
void output(int *arrayPtr, int size){
int small;
int i, j;
int *newArray;
newArray = new int[size];
for (i = 0; i < size; i++){
*newArray[i] = arrayPtr[i];
}
for (i = 0; i < size; i++){
small = *newArray[i];
for (j = 0; j < size; j++){
if (*newArray[j] < small){
*newArray[j] = small;
}
std::cout << small;
}
int number = small;
removeNumber(*& arrayPtr, number, size);
}
}
我覺得我似乎完全缺少一些東西,但是我將不勝感激任何幫助或想法!
small = *newArray[i];
那應該是:
small = newArray[i];
(在您比較/分配*newArray[i]
的其他地方也是如此
您的第一個操作是首先取消引用newArray,這意味着它獲取數組中第一個元素的值,然后嘗試對其進行索引。 該元素不是指針,因此這當然會失敗。 索引時,它還隱式取消引用指針。 您還可以編寫:
small = *(newArray + i);
但是,通常只在需要實際指針時才使用指針算術,因為如果需要該值,則索引更易於讀取。
遍歷您的代碼,似乎還有其他一些事情:
for (i = 0; i < size; i++){
*newArray[i] = arrayPtr[i];
}
這可能會編譯,但是我認為這是不對的,我猜你的意思是:
for (i = 0; i < size; i++){
newArray[i] = arrayPtr[i];
}
也:
removeNumber(*& arrayPtr, number, size);
在技術上這是正確的, *&
首先返回一個指針引用,然后轉回並再次取消引用。 如果編譯器對它進行了優化,我不會感到驚訝,但這是不必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.