Could you help me understand Pointers please?
I know this has been asked previously but one thing that these other questions didn't touch upon is why
Allow me to explain. I just ran through a tutorial that outputted integers and pointers to show you how to do it.
int anInteger = 50;
int *anIntPointer = &anInteger;
So, to set up a pointer I assign a variable value as normal, and then I 开发者_如何学JAVAassign that variable to a pointer. This I understand, but as I've already said, this is the how not the why.
If I wanted to return the value 50
I could just NSLog
anInteger
so why would I need a pointer. Why would I need to NSLog
*anIntPointer
if I could just NSLog
anInteger
which does exactly the same thing?
Okay, I know this is very trivial and there are probably perfect circumstances to use a pointer, but so far no tutorial that I've read or watched will give me a perfect circumstance. They all deal with the how
Please help me find the why.
Pointers have many uses. One obvious one is that you want to call a function and have it modify one of your variables:
void f(int *i) { *i = 42; }
int g() { int i; f(&i); return i; }
Another is to return a large struct without a huge amount of copying:
struct big_struct *f() {
big_struct *bs = malloc(sizeof(big_struct));
// Populate the big_struct;
return bs;
}
Yet another is to manage arrays who's size you don't know at compile:
struct item *fetch_items(int n) {
item *i = malloc(n*sizeof(item));
load_items(i, n);
return i;
}
Still another is recursive data types, such as linked lists:
struct node {
int value;
struct node *next;
};
And this is just a sampling. Pointers are like nails to a carpenter. They are a key tool in almost any non-trivial programming problem.
The main reasons why we use pointers (in C and C-derived languages) are:
- To mimic pass-by-reference semantics
- To track dynamically-allocated memory
- To create self-referential and dynamic data structures
- Because sometimes the language forces you to
To mimic pass-by-reference semantics: In C, all function arguments are passed by value. The formal parameters and the actual parameters are different objects in memory, so writing to the formal parameter has no effect on the actual parameter. For example, given the code
void swap(int a, int b)
{
int tmp = a; a = b; b = tmp;
}
int main(void)
{
int x = 2, y = 3;
printf("before swap: x = %d, y = %d\n", x, y);
swap(x, y);
printf("after swap: x = %d, y = %d\n", x, y);
return 0;
}
a
and x
are physically distinct objects; writing to a
does not affect x
or vice versa. Thus, the before and after output in the program above will be the same. In order for swap
to modify the contents of x
and y
, we must pass pointers to those objects and dereference the pointers in the function:
void swap(int *a, int *b)
{
int tmp = *a; *a = *b; *b = tmp;
}
int main(void)
{
int x = 2, y = 3;
printf("before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("after swap: x = %d, y = %d\n", x, y);
return 0;
}
a
and x
are still distinct objects in memory, but the expression *a
refers to the same memory as the expression x
; thus, writing to *a
updates the contents of x
and vice versa. Now the swap
function will exchange the contents of x
and y
.
Note that C++ introduced the concept of a reference, which sort of acts like a pointer but doesn't require an explicit dereference:
void swap(int &a, int &b)
{
int tmp = a; a = b; b = tmp;
}
int main(void)
{
int x = 2, y = 3;
std::cout << "before swap: x = " << x << ", y = " << y << std::endl;
swap(x, y);
std::cout << "after swap: x = " << x << ", y = " << y << std::endl;
return 0;
}
In this case, the expressions a
and x
do refer to the same memory location; writing to one does affect the other. This is a C++-ism, though.
I'm not familiar enough with Obj-C to know if they have a similar mechanism.
To track dynamically-allocated memory: The C memory allocation functions malloc
, calloc
, and realloc
, along with the C++ operator new
all return pointers to dynamically allocated memory. If you have to allocate memory on the fly, you have to use pointers to refer to it. Again, I'm not familiar enough with Obj-C to know if they use a different memory allocation mechanism.
To create self-referential and dynamic data structures: Aggregate types such as struct
or union
types cannot contain an instance of themselves; for example, you can't do something like
struct node
{
int value;
struct node next;
};
to create a linked list node. struct node
is not a complete type until the closing }
, and you cannot declare objects of an incomplete type. However, a struct can contain a pointer to an instance of itself:
struct node
{
int value;
struct node *next;
};
You can declare a pointer to an incomplete type, so this works. Each node in the list can refer to the node immediately following it. And since you're dealing with pointers, you can add or delete nodes from the list reasonably easily; you just have to update the pointer values, instead of physically moving data around.
I can pretty much guarantee that any container type in Obj-C uses pointer manipulation under the hood.
Because sometimes the language forces you to: In C and C++, an expression of array type will implicitly be converted to a pointer type in most circumstances. Array subscripting is done in terms of pointer arithmetic; the expression a[i]
is evaluated as though it were written *(a + i)
. IOW, you find the address of the i'th element after a
and dereference it.
Pointers are not specific to Objective-C, in fact they are used in C and [usually not so much C++]. Basically, it is how you pass objects by reference.
void thisFunctionModifiesItsArgs(int *x, int *y, int *z)
{
*x = 4;
*y = *z;
*z = 100;
}
int main()
{
int a = 0;
int b = 1;
int c = 2;
thisFunctionModifiesItsArgs(&a, &b, &c);
// now, a = 4, b = 2, and c = 100
}
the most obvious reasons:
1) you want the object pointed to to live beyond the scope of its use, so you create an allocation. accessing the int's address beyond its scope is asking for trouble -- the address is likely used by something else at that point. if you create a unique memory location for it, that problem is solved (or... maybe displaced).
2) you want to pass it by reference/pointer/address. this is useful to mutate an object, or as an optimization when the type is large.
3) support for polymorphism and/or opaque types
4) pointer to implementation (abstraction, dependency reduction)
and on... (i wouldn't expect you to understand all those cases at this stage)
so, the example you show is so trivial that it does not represent (any of) those cases -- it only attempts to introduce the syntax.
there are many cases, and they are used regularly in real world C, C++, ObjC, etc. programs for many different reasons.
A simple answer: because there are variables that are more complex than simple integers. The tutorial is giving you a very simple case to explain the concept, but the simple case they describe would almost never be used.
Justin's answer is spot on for what you're asking. If you need a good tutorial then I recommend chapter 5 of "Beginning Mac Programming" which explains how the memory addressing works and how this is essential for working with pointers, and the reasons why.
Computer Science 001
Computers (the computer chip) can only do three things, but they can do them million or even billions of times per second.
They can store information (a number) into memory. They can do arthimetic on those numbers. They can make simple decsions based on the arthimetic, like if a = b then go to address X.
Thats it.
A very simple analogy I use to explain pointers to beginners in assembler programming is to think of memory like a row of mailboxes. The first mailbox has address 0 and the next is one plus and so forth.
When a computer starts up, it is told to go to mailbox 0 and get the content.
The content can be information or a command, mailbox 0 always holds a command. The command might be Go to mailbox 1 and get its content.
The content of a mailbox can only hold so much information, just like a real mailbox can only hold so much information. If the postman need to deliver a package for example, he will put a notice in the mailbox to go to the post office to pick it up. The notice is like a pointer. The pointer does not hold the information, the real information is located where the pointer says it is located, in this case the post office.
You could even get to the post office to find out there is nothing but another pointer to another location. We would call that a "handle" or a pointer to a pointer.
If you want to copy a byte sequence from one place to other place, (naturally) you have to know the source and destination addresses. To express it in the language's abstraction level, you can use pointers, which represents the memory locations.
Beside notes has been written already, in lower levels, pointers are very often used. A very simple example: Writing to the 80x25 screen. For example the base address of the screen is 0xb8000, where the first character of the screen is stored. You can use pointers, with wich you can write a character to the appropriate position in the screen. e.g. : unsigned short* sc = (unsigned short*)0xb8000; *sc = 'A' | (attr) << 8;
. And so on...
N.B.: Pointers embodies indirection, and it is possible, you can have "multiple" pointers: ** (imagine the C main functions signature, and the char** in it!). Or e.g. you want to create a list structure with malloc in a separate function. Then you can pass a struct list** or what have you parameter and in the function you can assign a value (a memory address) to the list, which means you have created the list in the memory.
精彩评论