C++/pointers and arrays
what are they and what do they do?can you give me an example?
Hello Raymond, thank you for the question.
A pointer is a type of variable that can store a memory address as its value. Pointers can be of any time. Let's take a look using int as an example.
int x = 5;
int *y = &x;
cout << y << endl;
cout << *y; // Prints 5
A pointer named y is declared and set to the address of the x variable with the & operator. When you cout the y variable, it prints the memory address it is set to, because that's what it stores. However, you can dereference the pointer with the * operator. This returns the value that is actually stored at the memory address, printing 5.
An array is a continuous chunk of memory of the same type. The number of elements in the array is specified when it is created.
This creates 5 ints. To access items in the array, you index it with 's. In C++, arrays begin at index 0.
x = 1;
x = 2;
x = 3;
x = 4;
x = 5;
// Use a loop to print the values in the array
for(int i = 0; i < 5; i++)
cout << x[i] << endl;
This would print the value stored at each index in the array.
I hope this information was helpful.