[英]Pointer to Elements of an Array printing the memory address rather than the value of the element
I am currently writing a program for a class that takes user input to either add or remove a number from a dynamic array, and then print all the values of the array in ascending order. 我目前正在为一个类编写程序,该类需要用户输入以从动态数组中添加或删除数字,然后以升序打印该数组的所有值。
From what I have already researched, all I need to do to get the value of the element in the array to print is to ensure the dereference operator is inserted next to the pointer name. 根据我的研究,要获取要打印的数组中元素的值,我要做的就是确保将取消引用运算符插入指针名称旁边。 However, when done as below ( newArray[i]) I get a compile-time error saying that the operand to the right of the ' ' must be a pointer, even though newArray is declared as pointer at the beginning of the function.
但是,当按如下方式进行操作时( 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);
}
} }
I feel like there is something totally obvious I am missing, but I would greatly appreciate any help or ideas!! 我觉得我似乎完全缺少一些东西,但是我将不胜感激任何帮助或想法!
small = *newArray[i];
That should just be: 那应该是:
small = newArray[i];
(Same thing in the other places you compare/assign *newArray[i]
(在您比较/分配
*newArray[i]
的其他地方也是如此
What your first operation is doing is first dereferencing newArray, which means it gets the value of the first element in the array, and then attempting to index that. 您的第一个操作是首先取消引用newArray,这意味着它获取数组中第一个元素的值,然后尝试对其进行索引。 The element is not a pointer, so this of course fails.
该元素不是指针,因此这当然会失败。 When you index, it also implicitly dereferences the pointer.
索引时,它还隐式取消引用指针。 You could also write:
您还可以编写:
small = *(newArray + i);
However, generally you only use pointer arithmetic when you need the actual pointer, since indexing is easier to read if you need the value. 但是,通常只在需要实际指针时才使用指针算术,因为如果需要该值,则索引更易于读取。
Going through your code, a few other things seem off: 遍历您的代码,似乎还有其他一些事情:
for (i = 0; i < size; i++){
*newArray[i] = arrayPtr[i];
}
This might compile but I don't think it is right, I'm guessing you mean: 这可能会编译,但是我认为这是不对的,我猜你的意思是:
for (i = 0; i < size; i++){
newArray[i] = arrayPtr[i];
}
Also: 也:
removeNumber(*& arrayPtr, number, size);
While this is technically correct, *&
first returns a pointer reference, then turns around and dereferences it again. 在技术上这是正确的,
*&
首先返回一个指针引用,然后转回并再次取消引用。 I wouldn't be surprised if the compiler optimizes it away anyway, but it is unnecessary. 如果编译器对它进行了优化,我不会感到惊讶,但这是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.