Wednesday, December 4, 2013

Arrays ( Learn C Programming )


A C array (K&R 5.3) consists of multiple elements of the same data type. An array declaration states the data type of the elements, followed by the name of the array, along with square brackets containing the number of elements:

    int arr[3]; // means: arr is an array consisting of 3 ints

To refer to an element of an array, use the array’s name followed by the element number in square brackets. The first element of an array is numbered 0. So we can initialize an array by assigning values to each element in turn:

    int arr[3];
    arr[0] = 123;
    arr[1] = 456;
    arr[2] = 789;

Alternatively, you can initialize an array at declaration time by assigning a list of values in curly braces, just as with a struct. In this case, the size of the array can be omitted from the declaration, because it is implicit in the initialization (K&R 4.9):
    int arr[] = {123, 456, 789};
Curiously, the name of an array is the name of a pointer (to the first element of the array). Thus, for example, having declared arr as in the preceding examples, you can use arr wherever a value of type int* (a pointer to an int) is expected. This fact is the basis of some highly sophisticated C idioms that you almost certainly won’t need to know about (which is why I don’t recommend that you read any of K&R Chapter 5 beyond section 3).
Here’s an example where a C array might be useful when programming iOS. The func‐ tion CGContextStrokeLineSegments is declared like this:
Arrays in C programming
        Figure 1-1. Pointers and assignment

 void CGContextStrokeLineSegments (
       CGContextRef c,
       const CGPoint points[],
       size_t count
);

The second parameter is a C array of CGPoints. That’s what the square brackets tell you. So to call this function, you’d need to know at least how to make an array of CGPoints. You might do it like this: 

CGPoint arr[] = {{4,5}, {6,7}, {8,9}, {10,11}};
Having done that, you can pass arr as the second argument in a call to CGContextStroke-
LineSegments.
Also, a C string, as I’ve already mentioned, is actually an array. For example, the NSString method stringWithUTF8String: takes (according to the documentation) “a NULL- terminated C array of bytes in UTF8 encoding;” but the parameter is declared not as an array, but as a char*. Those are the same thing, and are both ways of saying that this method takes a C string.
(The colon at the end of the method name stringWithUTF8String: is not a misprint; many Objective-C method names end with a colon. 

No comments:

Post a Comment