Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 14: Understanding Arrays and Pointers

C pointers and arrays are closely related; so closely, in fact, that they are often interchangeable! However, this does not mean pointers and arrays are identical. We will explore this relationship and why we might want to use either array notation or pointer notation to access array elements. Most often, we will need to understand this relationship when we pass arrays to functions. So, understanding the interchangeability of arrays and pointers will be essential to making any function that manipulates arrays more flexible and expressive.

Having read two previous chapters, Chapter 11Working with Arrays, and Chapter 13Using Pointers, is essential to understanding the concepts presented here. Please do not skip those chapters before reading this one.

The following topics will be covered in this chapter:

  • Reviewing the memory layout of arrays
  • Understanding the relationship between array names and pointers...

Technical requirements

Continue to use the tools you chose from the Technical requirements section of Chapter 1Running Hello, World!.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter14.

Understanding array names and pointers

As we have seen, elements of arrays can always be accessed via indices and traversed by means of an integer offset from the zeroth element. Sometimes, however, it is more convenient to access array elements via a pointer equivalent.

Let's begin by declaring an array and two pointers, as follows:

const int arraySize = 5;
int       array[5] = { 1 , 2 , 3 , 4 , 5 };
int*      pArray1  = NULL;
int*      pArray2  = NULL;

We have declared a contiguous block of arraySize, or 5, which are elements that are integers. We don't use arraySize in the array declaration because that would make the array a variable-length array (VLA) that cannot be initialized in this way. We have also declared two pointers to integers—pArray1 and pArray2. In the memory on my...

Understanding array elements and pointers

Individual elements of an array can be accessed either with array notation or via pointers.

We have already seen how to access the elements of array using array notation—[ and ], as illustrated in the following code snippet:

array[0] = 1;  // first element (zeroth offset)
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;  // fifth element (fourth offset)

These statements assign 1..5 values to each element of our array, just as the single initialization statement did when we declared array[5].

Accessing array elements via pointers

Arithmetic can be performed with addresses. Therefore, we can access the elements of array using a pointer plus an offset, as follows:

*(pArray1 + 0) = 1;  // first element (zeroth offset)
*(pArray1 + 1) = 2;  // second element (first offset...

Operations on arrays using pointers

Before this chapter, the only pointer operation we had used with arrays was assignment. Because we can perform simple arithmetic on pointers—addition and subtraction—these operations conveniently lend themselves to array traversal. 

Using pointer arithmetic

An integer value in pointer arithmetic represents the element to which the pointer points. When an integer is added to a pointer, the integer is automatically converted into the size of the pointer element in bytes and added to the pointer. This is equivalent to incrementing an array index. Put another way, incrementing a pointer is equivalent to incrementing the index of an array. 

Even though pointers are nearly identical to integers—they are positive, whole numbers that can be added, subtracted, and compared—they are treated slightly differently from integers when pointer arithmetic is performed. The following cases...

Introducing an array of pointers to arrays 

Before finishing this chapter, it is worth introducing the concept of an array of pointers to arrays. This may be thought of as an alternate 2D array. Such an array is somewhat different in memory than the standard arrays that we have so far encountered. Even though its memory representation is different, we access this alternate array in exactly the same way as we would a standard 2D array. Therefore, some caution is required when traversing the two kinds of arrays.

We declare a standard 2D array in the following way:

int arrayStd[3][5];

We have allocated a contiguous and inseparable block of 15 integers, which has 3 rows of 5 integers. Our conceptual memory picture of this is a single block referenced via a single name, arrayStd, as follows:

Figure 14.5 – A standard, contiguous 2D array

To declare an alternate 2D array using arrays of pointers, we would do the following:

...

Summary

In this chapter, we used the concepts introduced in two earlier chapters, Chapter 11Working with Arrays, and Chapter 13Using Pointers, to learn how array names and pointers are related and interchangeable.

We have seen various memory layouts of arrays and pointers and used pointers in various ways to access and traverse arrays, both directly and via function parameters. We also have seen how pointer arithmetic pertains to elements of the array and is a bit different from integer arithmetic. We learned about some of the similarities and differences between a 2D array (a contiguous block of elements) and an array of pointers to sub-arrays (a collection of scattered arrays indexed by a single array of pointers). Finally, we looked at a set of simple programs that illustrate as well as prove the concepts we have learned.

Having explored arrays and pointers and their interrelationship, we are now ready to put all of these concepts to good...

Questions

  1. Are array notation and pointers identical?
  2. When you increment an array index by 1, what does that do?
  3. When you increment a pointer to an array element by 1, what does that do?
  4. Is this array always contiguous: int arr[3][5]?
  5. Are the elements of an array of pointers to other arrays always contiguous?
  6. If we pass a pointer to an array as a function parameter, must we use pointer notation to access the elements of the array?
  7. Does C remember the size of any array?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay