I'm pretty new to C so maybe I'm using pointers incorrectly. I'm working on a larger program and where I'm running into an issue where a pointer, pointing at the first element of an array is constantly changing as the array changes (using a PriorityQueue, so it's constantly being rearranged and so I'm running into issues).
I've made a very basic example of what's going on:
#include <stdio.h>
int main() {
int testArray[] = {0, 1, 2, 3};
int *pFirstElement = &testArray[0];
printf("My first element: %d\n", *pFirstElement); // Prints 0
testArray[0] = 9;
printf("My first element: %d", *pFirstElement); // Prints 9 -> I want it to print 0
return 0;
}
I'd like a way so that pFirstElement does not get reassigned until I manually reassign pFirstElement to be the first element of the array. Basically, modifications to the array should not change the value of pFirstElement. Is it because a pointer is pointing to the memory address of testArray[0]
, and instead should I not be using a Pointer?
The reason I used a pointer is that I can initialize it to NULL, and then a use case for my PriorityQueue is if the pointer is NULL, I know I need to dequeue basically. Not sure how else I could do that logic.
Any advice is helpful, thanks!
CodePudding user response:
Since pFirstElement
is simply a reference to the memory in which first element of the array is stored, reassigning the first element of the array will change the value that pFirstElement
is pointing to.
Setting an int
variable instead of an int *
to testArray[0]
instead of &testArray[0]
will create a copy of the data instead of simply storing a new reference to it. The copy is now independent of the data in testArray
.
Creating a copy of the data is the only way. A pointer by itself cannot remember past values of the memory it points to.
CodePudding user response:
The variable pFirstElement
points to the position in memory, where the first array element is. If you now access the value the pointer points to, you access the first element of the array. If you simply want a copy of first element use int firstElement = testArray[0];
, otherwise *pFirstElement = ...
is equivalent to textArray[0] = ...
.