Chuyển đến nội dung

Bài 8 · Language Basics

Pointers and Structs

Understand pointers, addresses, C arrays, structs and CGPoint-style value types in Objective-C, and see why every object is really a pointer to heap memory.

Objective-C objects are pointers, so a solid grasp of C pointers explains nearly every surprise in the language: why == compares addresses, why you write NSString *, and why nil is just a null pointer. This lesson also covers C arrays and structs, which Cocoa uses for lightweight values such as CGPoint, CGSize, NSRange and CGRect.

What a pointer is

A variable lives at some address in memory. A pointer is a variable that stores such an address. & takes the address of a variable and * follows a pointer to the value it points at:

OBJECTIVEC
int age = 30;
int *p = &age;     // p holds the address of age

NSLog(@"%d", *p);  // 30, reading through the pointer
*p = 31;           // changes age itself

Declaring int *p means "p points to an int". A pointer that points nowhere is set to NULL (or nil for objects). Following a null pointer in C crashes; following nil in a message is safe.

Why pass pointers

C passes arguments by value, so a function receives a copy. To let a function change the caller's variable, give it the address:

OBJECTIVEC
void increment(int *value) {
    *value += 1;
}

int count = 0;
increment(&count);   // count is now 1

Cocoa uses this pattern for "out parameters", most famously NSError **:

OBJECTIVEC
NSError *error = nil;
BOOL ok = [data writeToFile:path options:0 error:&error];
if (!ok) { NSLog(@"%@", error); }

The method receives the address of your error variable (a pointer to an object pointer) and may fill it in.

Objects are pointers

When you write NSString *name = @"Ada";, the variable name holds an address, and the string's bytes live elsewhere on the heap. Copying the variable copies only the address:

OBJECTIVEC
NSMutableString *a = [NSMutableString stringWithString:@"hi"];
NSMutableString *b = a;     // b and a point at the same object
[b appendString:@"!"];
NSLog(@"%@", a);            // hi!

Both names refer to one object; there is no second copy. This is the difference between a reference (objects) and a value (ints and structs, which copy completely on assignment).

C arrays and pointer arithmetic

A C array is a block of elements side by side. Its name decays to a pointer to the first element, and adding 1 to a pointer moves it by one element:

OBJECTIVEC
int numbers[4] = {10, 20, 30, 40};
int *p = numbers;
NSLog(@"%d %d", *p, *(p + 2));   // 10 30
NSLog(@"%d", numbers[2]);        // 30, the same as *(numbers + 2)

sizeof(numbers) / sizeof(numbers[0]) gives the element count, but only where numbers is still an array, not after it has been passed to a function. C arrays are not bounds-checked: reading numbers[10] is undefined behavior. For lists of objects, use NSArray (covered in the Foundation chapter).

Structs

A struct groups named fields into one value:

OBJECTIVEC
typedef struct {
    double x;
    double y;
} Point;

Point p = {3.0, 4.0};
p.x = 5.0;

Point *pp = &p;
pp->y = 9.0;      // arrow accesses a field through a pointer

Assigning a struct copies all fields. Structs can be passed to functions and returned by value, and they can nest.

Cocoa provides several ready-made structs with creation functions:

OBJECTIVEC
CGPoint origin = CGPointMake(10, 20);
CGSize size = CGSizeMake(100, 50);
CGRect frame = CGRectMake(10, 20, 100, 50);
NSRange range = NSMakeRange(2, 5);   // location 2, length 5
NSLog(@"%@", NSStringFromRect(frame));

(CGPoint and friends come from CoreGraphics on Apple platforms; on GNUstep similar NSPoint, NSSize and NSRect types exist.)

Structs cannot hold ARC-managed object pointers unless special care is taken, and they cannot be put into an NSArray directly; you wrap them in NSValue, as shown in Literals and Boxing.

void pointers and casting

void * is a pointer to unspecified data. It is how C-style APIs pass context pointers. You must cast it back to the right type before use. Objective-C also uses id for "pointer to any object".

Stand-in: pointers, out-parameters and sharing

This C program shows address-of, dereference, an out-parameter, and two names for one thing:

C Stand-in (C): pointers and out-parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: structs and handles

An Objective-C object behaves like a struct accessed through a pointer. This program uses a heap struct and two "references" to it, matching the NSMutableString example above, and a value struct that copies.

C Stand-in (C): value copy versus shared reference

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Dereferencing an uninitialized or NULL C pointer.
  • Returning the address of a local variable, which dies when the function returns.
  • Believing NSMutableString *b = a; makes a copy. Use [a mutableCopy] for that.
  • Reading past the end of a C array.
  • Forgetting * when declaring an object variable.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does int *p = &x; store in p?

    & takes the address; p now points at x.
  2. 2. After NSMutableString *b = a;, what is true?

    Assigning an object pointer copies only the address, so both names share one object.
  3. 3. How do you access field y of a Point *pp?

    The arrow operator reaches a field through a pointer. It is the same as (*pp).y.
  4. 4. Which is a typical use of the NSError ** parameter?

    The caller passes &error, and the method may assign to *error.

Summary

  • A pointer stores an address; & gets one and * follows one.
  • Objects in Objective-C are pointers to heap memory, so assignment shares and does not copy.
  • Pass &variable to let a function change a caller's value, as with NSError **.
  • Structs are value types that copy on assignment; Cocoa uses them for points, sizes, rectangles and ranges.
  • C arrays are not bounds-checked.

Next: Literals and Boxing

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.