Fundamental C - Simple Arrays |
Written by Harry Fairhead | |||
Monday, 09 September 2019 | |||
Page 1 of 2 This extract, from my new book on programming C in an IoT context, explains the basics of the array, This is not as simple as in other languages because it is so simple. Fundamental C: Getting Closer To The MachineNow available as a paperback and ebook from Amazon.
Also see the companion volume: Applying C <ASIN:1871962609> <ASIN:1871962463> <ASIN:1871962617> <ASIN:1871962455>
In this chapter we take a look at how arrays are used and how pointers play a role. This is a first look at pointers as it is important that you know they exist and what they are, but there is a full chapter later on which explains the more advanced aspects of pointers. In the next chapter we look at the practicalities of using strings. The ArrayThe array solves many problems that would be next to impossible without it. Suppose you need to keep track of the scores of three users. You might well try: user1=42; user2=43; user3=44; This works, but now generalize it to 100 users or a 1000. Not easy, but with an array it’s very easy. An array is a data structure that consists of lots of repeats of a basic element. Any element can be accessed using a numeric index. So, for example, the previous user scores using an array would be written: user[1]=42; user[2]=43; user[3]=44; Notice that the array is called user and it has three elements. In C you have to declare an array and fix its size before you can use it using an instruction like: type name[number of elements]; So for example to declare an array of three ints you would use: int user[3]; The only potentially confusing part is that the array index starts at zero. This means that the declaration creates user[0], user[1] and user[2]. Notice that the declaration gives the number of elements not the value of the final index. It is important to realize that an array cannot increase or decrease in size once it has been declared. There are also some confusing rules about how you can specify the size of an array. For arrays defined at file level, i.e. not within a function, the size must be specified as a constant expression. A constant expression is one that can be evaluated at compile time as all of the values are known, e.g. 2*3. For an array defined within a function, you can use an expression that can only be evaluated at runtime, but only in C99 or later – this is known as a variable length array or VLA. In C89 the GCC compiler will allow runtime expressions and only warn you that you shouldn’t do this if you add -pedantic to the compiler options. What this means is that you can include arrays in functions and set the size when the function is used. For example: int sum(int n){ int myArray[n]; . . . } is fine in C99 and later and works in GCC’s implementation of C89 even if it isn’t part of the standard. Notice that as n isn’t defined at compile time you cannot say what the size of the array is before the program is run. When the function is completed the array is destroyed as is the case for any local variables. If the function is called again then the array is recreated possibly with a different size. In most cases VLAs are best avoided if at all possible. It doesn’t matter how you specify the size of an array, once declared it cannot change its size without being destroyed and recreated. You can also initialize an array using curly brackets: int myArray[6]={0,1,2,3,4,5}; This sets myArray[0] to zero, myArray[1] to one and so on. If you don’t provide enough initializer values then the remaining elements are set to zero. This can be used to set an entire array to zero. For example: int myArray[1000]={0}; notice that this only works for zero. C99 also allows you to specify starting positions for the initialization. For example: int myArray[1000]={0,1,2, [10]=10,11,12,13,[500]=500,501}; This sets the first three elements to 0,1 and 2, then zeros elements up to 9 and stores 10 in element 10, 11 in 11 and so on, then zeros 14 up to element 500 where it stores 500, and 501 in element 501. You can see the idea, the initialization restarts at the indicated position in square brackets and any elements not initialized are set to zero. If you don’t specify the size of the array then it is made large enough to hold all of the initial values: int myArray[]={0,1,2,3,4,5}; Also notice that while ints have been used in the examples, all of this works no matter what the types of the elements are. For example: float myArray[]={1.0f,2.0f,3.0f}; creates a three element array of floats. Arrays and For LoopsSo now you know how to create an array and how to initialize one. However, how would you initialize an array with 1000 elements? The answer, as it is to many uses of the array, is to use a for loop. Arrays and for loops were made for each other. For example, to set a 1000-element array to 1 you would use: int myArray[1000]; for(int i=0;i<1000;i++){ myArray[i]=1; } The array index isn’t restricted to be a simple variable, it can be an expression. You can also assign an expression to an array element. It is this freedom to use expressions that makes C a powerful language. In general anywhere you can use a variable or a literal you can use an expression. For example, to set the array elements equal to 0, 2, 4, and so on you would use: int myArray[1000]; for(int i=0;i<1000;i++){ myArray[i]=2*i; } One of the things you have to learn to use C effectively is how to construct index expressions that give you the array elements you want to use. For example, assuming i runs from 0 to the last element: 2*i gives you all the even elements and: 2*i+1 gives you all the odd elements. For example, to set all the even elements to 1 and the odd elements to -1 you would use: int myArray[1000]; for(int i=0;i<500;i++){ myArray[2*i]=1; myArray[2*i+1]=-1; } Once you have seen this sort of approach then you can usually work out an expression that gives you what you need. |
|||
Last Updated ( Monday, 09 September 2019 ) |