Computer Science
Pointers and Arrays
Pointers and arrays are closely related concepts in computer programming. A pointer is a variable that stores the memory address of another variable, while an array is a collection of variables of the same data type that are stored in contiguous memory locations. Pointers can be used to manipulate arrays and access their elements.
Written by Perlego with AI-assistance
11 Key excerpts on "Pointers and Arrays"
- eBook - ePub
Learn C Programming
A beginner's guide to learning C programming the easy and disciplined way
- Jeff Szuhay(Author)
- 2020(Publication Date)
- Packt Publishing(Publisher)
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 to integer arithmetic. We learned about some of the similarities and differences between a two-dimensional 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 use in the next chapter. - eBook - ePub
- Jeff Szuhay(Author)
- 2022(Publication Date)
- Packt Publishing(Publisher)
Chapter 14 : Understanding Arrays and PointersC 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 11 , Working with Arrays , and Chapter 13 , Using 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
- Using pointers in various ways to access and traverse arrays
- Expanding the use of pointer arithmetic, specifically for array elements
- Creating an array of pointers to arrays and a two-dimensional (2D ) array to highlight their differences
Technical requirements
Continue to use the tools you chose from the Technical requirements section of Chapter 1 , Running 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. - eBook - ePub
- Yuan Dong, Fang Yang, Li Zheng(Authors)
- 2019(Publication Date)
- De Gruyter(Publisher)
Why do we need to set a pointer as a null pointer using the method above? This is because sometimes when declaring a pointer, there is no definite address value that can be assigned to it. Only when the program runs to a point does it assign an address value to this pointer. During the period from the birth of the pointer to the time it has a definite value, its value is random. If we wrongly use this random value as an address to access some memory location, it will lead to unexpected error. Therefore, in this situation we should first set the pointer as a null pointer.6.2.6Using Pointers to Process Array Elements
The addition and subtraction characteristics of pointers make them especially suitable for processing the same type of data that is stored in a continuous memory space. An array is a set of same-type variables that have some ordinal relation; array elements are stored continuously physically; and the array name is the starting address of the array. We can use pointers to do convenient and quick operations on arrays and array elements. For example,declares a one-dimensional array that stores five int -type elements. The array name array is the starting address of the array (the address of its first element). That is, array is the same as &array[0] . Five integers in the array are stored orderly, so we can access array elements by using the array name and some simple arithmetic operations. The array element whose subscript is i is * (array name+i) . For example, * array is array[0] , and * (array+3) is array[3] .Example 6.7: Suppose there is an array a of the int type, which has 10 elements. Use three methods to output all the elements.Program 1: Using array name and subscripts Program 2: Using array name and pointer operations Program 3: Using pointer variables The running results of the above programs are the same. And the result is:This example is very simple, and readers can analyze the running results themselves. Think carefully about the relationships and differences between the array name, subscripts of array elements, and pointers that point to array elements. - eBook - PDF
A Short Course in Computational Science and Engineering
C++, Java and Octave Numerical Programming with Free Software Tools
- David Yevick(Author)
- 2012(Publication Date)
- Cambridge University Press(Publisher)
Chapter 12 Pointers and dynamic memory allocation A pointer variable like a reference or array variable stores a memory address; however, this address can be arbitrarily changed, enabling the contents of any accessible memory location to be addressed and manipulated directly. While enabling access to all available resources, new and subtle types of errors arise. For example, when a program requests additional memory during runtime from the operating system, the address of the starting location to the new, dynamically allocated variable is returned. Since the value stored in a preexisting compiler- allocated pointer variable can be altered, the running program can preserve the address passed back by the operating system. However, if the pointer variable was defined within an inner block, it will be destroyed when the block terminates. The location of the dynamically allocated memory is then lost and the memory cannot subsequently be accessed or later freed. 12.1 Introduction to pointers A definition in C++ establishes the amount of memory space required for a variable and the interpretation of the value stored at this memory location. The value of a pointer variable is associated with the starting memory address of a variable of a specified type, i.e. the value of a pointer is a memory address. That is, a double pointer that stores a value such as 80000 interprets the 8-byte region from physical memory location 80000 to location 80007 as the storage location of a double variable. The amount of memory space reserved by any pointer variable equals the number of bits required to store a hardware memory address – on a 32-bit machine, an address requires 4 bytes so that applying the sizeof( ) function to any pointer yields 4. To define a pointer to a variable of e.g. type int, the notation int * is employed, where a pointer type is designated by a star. To define multiple pointer variables within the same statement, a star must precede each pointer. - eBook - PDF
C++ Programming
From Problem Analysis to Program Design
- D. Malik(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
Until now, you have studied only the first two data types. This chapter discusses the third data type called the pointer data type. You will first learn how to declare pointer variables (or pointers, for short) and manipulate the data to which they point. Later, you will use these concepts when you study dynamic arrays and linked lists. Linked lists are discussed in Chapter 17. Pointer Data Type and Pointer Variables Chapter 2 defined a data type as a set of values together with a set of operations. Recall that the set of values is called the domain of the data type. In addition to these two properties, until now, all of the data types you have encountered have one more thing associated with them: the name of the data type. For example, there is a data type called int. The set of values belonging to this data type includes integers that range between –2147483648 and 2147483647, and the operations allowed on these values are the arithmetic operators described in Chapter 2. To manipulate numeric integer data in the range –2147483648 to 2147483647, you can declare variables using the word int. The name of the data type allows you to declare a variable of that type. Next, we describe the pointer data type. The values belonging to pointer data types are the memory addresses of your computer. As in many other languages, there is no name associated with the pointer data type in C11. Because the domain—that is, the set of values of a pointer data type—is the addresses (locations) in memory, a pointer variable is a variable whose content is an address, that is, a memory location and the pointer variable is said to point to that memory location. Pointer variable: A variable whose content is an address (that is, a memory address) and is therefore said to point to a memory address. Declaring Pointer Variables As remarked previously, there is no name associated with pointer data types. More- over, pointer variables store memory addresses. - 223 C H A P T E R 7 POINTERS AND STRUCTURES C H A P T E R G O A L S To be able to declare, initialize, and use pointers To understand the relationship between arrays and pointers To be able to convert between string objects and character pointers To become familiar with dynamic memory allocation and deallocation To use structures to aggregate data items C H A P T E R C O N T E N T S © Suzanne Tucker/Shutterstock. 7.1 DEFINING AND USING POINTERS 224 SYN Pointer Syntax 226 CE 1 Confusing Pointers with the Data to Which They Point 228 PT 1 Use a Separate Definition for Each Pointer Variable 229 ST 1 Pointers and References 229 7.2 ARRAYS AND POINTERS 230 ST 2 Using a Pointer to Step Through an Array 233 CE 2 Returning a Pointer to a Local Variable 234 PT 2 Program Clearly, Not Cleverly 234 ST 3 Constant Pointers 235 7.3 C AND C++ STRINGS 235 ST 4 Working with C Strings 238 7.4 DYNAMIC MEMORY ALLOCATION 240 SYN Dynamic Memory Allocation 240 CE 3 Dangling Pointers 242 CE 4 Memory Leaks 243 7.5 ARRAYS AND VECTORS OF POINTERS 243 7.6 PROBLEM SOLVING: DRAW A PICTURE 246 HT 1 Working with Pointers 248 WE1 Producing a Mass Mailing 249 C&S Embedded Systems 250 7.7 STRUCTURES 250 SYN Defining a Structure 251 7.8 POINTERS AND STRUCTURES 254 ST 5 Smart Pointers 256 224 In the game in the photo, the spinner’s pointer moves to an item. A player follows the pointer and handles the item to which it points—by taking the ball or following the instructions written in the space. C++ also has pointers that can point to different values throughout a program run. Pointers let you work with data whose locations change or whose size is variable. In the second part of this chapter, you will learn how to use structures. Unlike arrays, structures can be used to group values of different types together. Finally, you will see how to use pointers and structures to model interconnected data. 7.1 Defining and Using Pointers With a variable, you can access a value at a fixed location.
- eBook - ePub
Introduction to Windows® and Graphics Programming with Visual C++®
(with Companion Media Pack)
- Roger Mayne(Author)
- 2015(Publication Date)
- WSPC(Publisher)
In reality, like all variables of type float, the entries in Vector[5] each occupy four bytes in memory (where a “byte” contains eight “bits”, i.e. ones and zeros) with two bytes used for the number itself and two bytes used for its mantissa. One special feature of using pointers to specify addresses in memory is that incrementing a pointer will automatically move within memory from one variable in an array to the next. It is not necessary to worry about the byte-to-byte details. This is true regardless of the variable type (integer, float, double, etc.) as well for structures and objects which will be discussed shortly. This is also the reason why pointers are always declared in association with a particular type of variable, structure or object.Figure 2.3 “Pointing” to Locations in Memory for Entries in the Array Vector[5]2.2.3Using a pointer with a one-dimensional array
In Section 2.1 we worked with a simple one-dimensional array and in Section 2.2.2 we discussed the “pointer” concept for addressing the entries in an array. In this section we will bring the two ideas together in a simple program and use a pointer to allow a function to have direct access to an array. The program below is from the example project VecPointer that you can find in the folder Chap2\3_VecPointer. Double clicking on VecPointer.sln will make the file VecPointer.cpp available to you. The listing of the file is shown in Table 2.3 . The VecPointer example performs the same operations as the VectorG example of Section 2.1 . However, in this case, the array Vector is not declared globally. Instead, it is declared locally in main() and passed to the function now called PtVecFunction by use of a pointer to the array.In looking through the listing of VecPointer.cpp in Table 2.3 , we see that the floating point array Vector[5] is only declared locally in main() at line 08. Line 09 declares the floating point pointer PtVector. In line 10 the pointer PtVector is set to the address of the first entry in the array. In summary, after lines 08-10, the pointer PtVector contains the address of the array entry Vector[0].The function PtVecFunction is initially declared at line 04 and is shown in prototype form in lines 25-35. It has been prepared to manipulate the one-dimensional array by having access to it through a pointer. The input argument “float*” shown for PtVecFunction in line 04 means that a floating point pointer is expected as an input to PtVecFunction. In the redeclaration of PtVecFunction in line 25, the pointer is given the variable name Ptr for use within the function. The for loop of lines 30–34 then manipulates the contents of the array Vector[5] in line 32 using Ptr. It addresses each entry using the expression *(Ptr + i) and adds two to its contents. In this expression, the “*” should be read as “contents of” according to the discussion of Section 2.2.1 - eBook - PDF
- Ivor Horton(Author)
- 2014(Publication Date)
- Wrox(Publisher)
The contents of a variable are either entered from an external source, such as the keyboard, or calculated from other values. There is another kind of variable that does not store data that you normally enter or calculate, but greatly extends the power and flexibility of your programs. This kind of variable is called a pointer . What Is a Pointer? Each memory location in your PC has an address. The address provides the means for the hardware to reference that location. A pointer is a variable that stores the address of another variable of a given type. A pointer has a variable name just like any other variable and also has a type that des-ignates what kind of variables its contents refer to. Note that the type of a pointer variable includes the fact that it’s a pointer. A variable that is a pointer, that can hold an address of a location con-taining a value of type int , is of type ‘pointer to int ’. Declaring Pointers A definition for a pointer is similar to that of an ordinary variable, except that the pointer name has an asterisk in front of it to indicate that it’s a pointer. For example, to define a pointer pnumber of type pointer to long , you could use the following statement: long* pnumber; This definition has been written with the asterisk close to the type name. If you want, you can also write it as: long *pnumber; The compiler won’t mind; however, the type of pnumber is ‘pointer to long ’, which is often indi-cated by placing the asterisk close to the type name. Whichever way you choose to write a pointer type, be consistent. You can mix definitions of ordinary variables and pointers in the same statement. For example: long* pnumber, number {99}; This defines pnumber of type ‘pointer to long ’ as before, and also defines the variable number , of type long . - No longer available |Learn more
C Programming
A Self-Teaching Introduction
- Rajiv Chopra(Author)
- 2017(Publication Date)
- Mercury Learning and Information(Publisher)
These addresses are stored into formal argu- ments, which are nothing other than pointer variables. Now whatever changes are made in the formal arguments are reflected directly to the actual arguments. 3.8 ARRAY OF POINTERS Like a normal data-type array, we can also create an array of pointers. If we want to store the addresses of 5-integer variables, we write: int *ptr[5]; This declaration reserves 10 bytes of contiguous memory for 5 pointers. For example, consider the following program: #include void main( ) { int a = 10, b= 20, c=30,d= 40,e= 50}; int ptr[5]; ptr[0] = &a; ptr[1] = &b; ptr[2] = &c; ptr[3] = &d; ptr[4] = &e; for(int i=0; i<5;i++) printf(”\nValue stored at address=”, *ptr[i]); } OUTPUT (after running): Value stored at address = 10 Value stored at address = 20 Value stored at address = 30 Value stored at address = 40 Value stored at address = 50 244 • C PROGRAMMING 3.9 PASSING ARRAYS AS ARGUMENTS Just like ordinary variables, we can also pass a complete array by using its base address. For example, #include void main( ) { int a[5]; void aread(int *, int); void adisplay(int*, int); printf(“\nEnter any 5 integers:”); aread(a, 5); printf(“Array elements are :”); adisplay(a, 10); } void aread(int *aptr, int n) { for (int i=0; i - eBook - PDF
- John Armstrong(Author)
- 2017(Publication Date)
- Chapman and Hall/CRC(Publisher)
Chapter 11 Arrays, Strings, and Pointers One useful way to view C++ is as a collection of languages: (i) the C language; (ii) an object-oriented programming language; (iii) a template programming language. This chapter is about some of the C language aspects of C++. We have ig-nored them so far, because you should focus your efforts on the object-oriented features of C++. Similarly we will not discuss the template programming fea-tures until Chapter 17. Pointers are a central feature of the C language. They are a tool for directly manipulating computer memory. You will not find them in a more modern pure object-oriented programming language like Java. The feature is omitted from other languages because pointer-based programs are typically harder to understand than object-oriented programs. Most of what you learn in this chapter you should never use directly. The only thing you need to use is shared_ptr . We will discuss this towards the end of the chapter. Unfortunately, to understand shared_ptr you must first understand ordinary pointers. There are three other motivations for studying the material in this chapter. (i) The first is that C++ was originally designed for people with C pro-gramming experience. So some C++ code is designed to be intuitive to use if you have experience with C pointers. If you don’t study pointers, you will find things like the C++ standard library very unintuitive. (ii) The second is that job interviewers may assume that you know C and so may ask some trick questions about pointers, so it is good to be prepared! (iii) The third is that to write maximally efficient C++ programs it can be helpful to manage memory consciously. Pointers are a tool for direct memory manipulation. Because this chapter and the next are more about C programming than object-oriented programming, we’ve temporarily abandoned developing FM-Lib for this chapter. Instead the project PointerExamples.zip contains all code for this chapter. 175 - eBook - PDF
C++ Programming
Program Design Including Data Structures
- D. Malik(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
The statement stdPtr++; increments the value of stdPtr by 40 bytes. The increment operator increments the value of a pointer variable by the size of the data type or structure to which it is pointing. Similarly, the decrement operator decre-ments the value of a pointer variable by the size of the data type or structure to which it is pointing. Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 Dynamic Arrays | 837 1 2 Moreover, the statement p = p + 2; increments the value of p (an int pointer) by 8 bytes. Thus, when an integer is added to a pointer variable, the value of the pointer variable is incremented by the integer times the size of the data type or structure to which the pointer is pointing. Similarly, when an integer is subtracted from a pointer variable, the value of the pointer variable is decremented by the integer times the size of the data type or structure to which the pointer is pointing. Pointer arithmetic can be very dangerous. Using pointer arithmetic, the program can acci-dentally access the memory locations of other variables and change their content without warning, leaving the programmer trying to find out what went wrong. If a pointer variable tries to access either the memory spaces of other variables or an illegal memory space, some systems might terminate the program with an appropriate error message. Always exercise extra care when doing pointer arithmetic. Dynamic Arrays In Chapter 8, you learned how to declare and process arrays. The arrays discussed in Chapter 8 are called static arrays because their size was fixed at compile time. One of the limitations of a static array is that every time you execute the program, the size of the array is fixed, so it might not be possible to use the same array to process differ-ent data sets of the same type. One way to handle this limitation is to declare an array that is large enough to process a variety of data sets.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.










