Reputation: 1265
This is my very simple introductory code to C++ pointers,
#include <iostream>
int main(int argc, const char* argv[])
{
int *p = 0, numbers[5];
*p = 10;
*(p+1) = 20;
*(p+2) = 30;
*(p+3) = 30;
*(p+4) = 40;
for (int i = 1; i < 5; i++)
numbers[i] = *(p + i);
for (int i = 1; i < sizeof(numbers); i++)
std::cout << numbers[i] << '\n';
return 0;
}
I am running this in Xcode and it shows "build succeeded" but gives me stack output and doesn't show me the actual result.
Upvotes: 0
Views: 139
Reputation: 24249
Pointers are variables which store a number, like any other, but because you tell the compiler it is a pointer, the compiler allows you to use that value as an address of things in memory and the language provides "dereferencing" as a way of saying "the value AT the address this variable describes".
Imagine you're going to the airport to catch a flight. You grab a post-it note and write down your flight number, and you take a second post-it with you for your gate.
The first post it is a "flight*" pointer and your second is a "gate*" but right now the gate* pointer is empty.
When you get to the airport, you look up your flight on the board and jot down the gate number. "3A". Now your gate* post-it is valid.
But the post-it itself is NOT your gate, it just points to it: you still have to "dereference" the post-it note to get to your flight - that is, walk across the airport to gate 3A :)
In programming, a variable can't be empty, so it has been agreed upon that a pointer with an address of 0 is "null" and "illegal". Programs crash when they attempt to use a null pointer. By convention there is a macro called "NULL" in C which is intended to distinguish "empty pointer" from the value 0. C++ inherited this but in C++11 they have introduced a new constant, "nullptr".
Your code opens with this:
int *p = 0;
Which catches a lot of people out. It looks like the same syntax as when we assign through a pointer:
*p = 10;
But what is actually happening is that you are declaring a variable p which is of type "int *" and assigning a value to p, not *p.
int *p;
p = 0;
*p = 10;
You need to point "p" at some integers for storage, either:
p = numbers;
but this will make p point to the same storage as numbers. But realize, then, that operations like
numbers[i] = *(p+i);
are now redundant -- if (p == numbers)
then *(p+i)
is the same as saying numbers[i]
.
Upvotes: 1
Reputation: 47794
Make p
point to a valid memory location before dereferencing
p = numbers;
And, following won't be required.
for(int i=1;i<5;i++)
numbers[i]=*(p+i);
Also, i
should start with 0 in for-loop
Upvotes: 4