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"

  • Learn Programming with C
    eBook - ePub

    Learn Programming with C

    An Easy Step-by-Step Self-Practice Book for Learning C

    • Sazzad M.S. Imran, Md Atiqur Rahman Ahad(Authors)
    • 2024(Publication Date)
    CHAPTER 3 Arrays and Pointers
    DOI: 10.1201/9781003302629-3
    IN C, AN ARRAY is used to hold multiple values of the same data type. The array could be one-dimensional, two-dimensional, or three-dimensional. On the other hand, pointer variables are used to hold addresses rather than values of variables. In terms of memory access, arrays and pointers are synonymous. The first element of an array is referred to by its name, whereas the value of a pointer points to any memory location.

    3.1 ARRAYS

    An array is a collection of data types that are all of the same kind. A single array variable can store, access, and handle a large amount of data. In the following C code, for example, int num[100];
    num is an integer type array with a total of 100 elements. Starting at 0 and continuing until n-1, each array element can be retrieved using appropriate indexing. The 4th, 5th, and 6th elements of the above num array, for example, are accessed with num[3], num[4], and num[5].
    We initialize the array in the same way that we would for any other data type variable.
    1. While declaration of the array: int num[4] = {5, 10, 9, 19}; or, int num[] = {5, 10, 9, 19};
    2. After declaration of the array: int num[4]; num[4] = {5, 10, 9, 19}; or, num[] = {5, 10, 9, 19};
    3. Interactively by the user after running the program. In that case, we usually use any of the C loops to access each element of the array. Example: int i, num[4]; for (i=0; i<4; i++) scanf(“%d”, &num[i]);
    When any array is declared, the array is organized such that all the array elements occupy contiguous space in memory. If the size of the integer data type is 4 bytes, then the memory organization of the array num[4] is as follows:

    3.2 2D ARRAYS

    A two-dimensional array is an array of arrays. It is also known as a matrix in C and is defined as a set of rows and columns. The following expression represents an integer type 2D array of matrix 2 × 4.
  • Learn C Programming
    eBook - ePub

    Learn C Programming

    A beginner's guide to learning C programming the easy and disciplined way

    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.
  • Learn C Programming
    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 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.
  • C++ Programming
    eBook - ePub
    • Yuan Dong, Fang Yang, Li Zheng(Authors)
    • 2019(Publication Date)
    • De Gruyter
      (Publisher)
    6Arrays, Pointers, and Strings
    After studying the concepts and applications of basic control structures, functions, and classes of C++, many problems can be described and solved. However, for large scales of data, especially when they are mutually correlated or are similar and correlated data, how to present and organize them efficiently remains a problem. The array type in C++ provides an effective way to organize objects of the same type.
    An important characteristic, which C++ inherits from C, is that we can directly use an address to access memory, and the pointer variable is an important data type for realizing this feature. Using pointers, we can conveniently process large amounts of data continuously stored in memory, achieve massive data sharing between functions at a comparatively low cost, and easily realize dynamic memory allocations.
    Using character arrays to make up the deficiency of string variables is an effective method inherited from C. However, from the object-oriented and security perspectives, strings represented by character arrays have deficiencies. Therefore, the standard class library of C++ provides the string class, which is a good example of expanding data types based on the class library.
    In this chapter, we will introduce the array type, pointer type, dynamic memory allocation, and how to store and process string data.

    6.1Arrays

    To understand the function of an array, please consider this problem: how does one store and process a series of n integers in a program? If n is small, for example, n is 3, we can easily declare three variables of the int type. If n is 10,000, then we need to declare 10,000 variables of int type to represent these 10,000 numbers by int
  • ANSI C Programming
    eBook - ePub

    ANSI C Programming

    Learn ANSI C step by step

    10 Arrays
    • What are Arrays A Simple Program Using Array
    • More on Arrays Array Initialisation Bounds Checking Passing Array Elements to a Function
    • Pointers and Arrays Passing an Entire Array to a Function The Real Thing
    • Two Dimensional Arrays Initialising a 2-Dimensional Array Memory Map of a 2-Dimensional Array Pointers and 2-Dimensional Arrays Pointer to an Array Passing 2-D Array to a Function
    • Array of Pointers
    • Three-Dimensional Array
    • Summary
    • Exercise
     
    T he C language provides a capability that enables the user to design a set of similar data types, called array. This chapter describes how arrays can be created and manipulated in C.
    We should note that, in many C books and courses, arrays and pointers are taught separately. I feel it is worthwhile to deal with these topics together. This is because Pointers and Arrays are so closely related that discussing arrays without discussing pointers would make the discussion incomplete and wanting. In fact, all arrays make use of pointers internally. Hence, it is all too relevant to study them together rather than as isolated topics.

    What are Arrays

    For understanding the arrays properly, let us consider the following program: #include <stdio.h> int main() {   int x;   x = 5;   x = 10;   printf ("x = %d\n", x);   return 0; }
    No doubt, this program will print the value of x as 10. Why so? Because, when a value 10 is assigned to x , the earlier value of x , i.e. 5, is lost. Thus, ordinary variables (the ones which we have used so far) are capable of holding only one value at a time (as in this example). However, there are situations in which we would want to store more than one value at a time in a single variable.
    For example, suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case, we have two options to store these marks in memory: (a) Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each variable containing one student’s marks.
  • C Programming
    eBook - ePub

    C Programming

    Learn to Code

    11 Pointers
    DOI: 10.1201/9781003188254-11

    11.1 Introduction

    A pointer is something that indicates or points. From the layman’s point of view a pointer is a long-tapered stick for indicating objects, as on a chart or a blackboard (Figure 11.1 ). Sometimes we use a laser pointer to point or show an object displayed on a screen (Figure 11.1). So, we can say a pointer is indirectly pointing to a device of our concerns.
    Figure 11.1 Pointing device.
    To understand the way in which pointers operate, it is first necessary to understand the concept of indirection. You are familiar with this concept from your everyday life. For example, suppose you need to buy a new computer for your department. In the company that you work for, all purchases are handled by the purchasing department. So, you call Mr. X in purchasing and ask him to order the new computer for you. Mr. X, in turn, calls the local supply store to order the computer. This approach to obtain your new computer is actually an indirect one because you are not ordering the computer directly from the supply store yourself.
    This same notion of indirection applies to the way pointers work in C. A pointer provides an indirect means of accessing the value of a particular data item. In C programming, a pointer is a variable that represents the location (rather than the value) of a data item, such as a variable or an array element. Pointers play an important role in the development process. A pointer has a number of useful applications. For example, pointers can be used to pass information back and forth between a function and its reference point. In particular, pointers provide a way to return multiple data items from a function via function arguments.

    11.2 Basic Knowledge

    Within the computer’s memory, every stored data item occupies one or more contiguous memory cells (i.e., adjacent words or bytes). The number of memory cells required to store a data item depends on the type of data item. For example, a single character will typically be stored in one byte (eight bits) of memory; an integer usually requires four contiguous bytes; a floating-point number requires four contiguous bytes; and a double-precision quantity requires eight contiguous bytes.
  • Composite Data Structures and Modularization
    eBook - ePub

    Composite Data Structures and Modularization

    Volume 2: Composite Data Structures and Modularization

    • Xingni Zhou, Qiguang Miao, Lei Feng(Authors)
    • 2020(Publication Date)
    • De Gruyter
      (Publisher)
    2  Pointers
    Main contents
    • Meaning, usage, and examples of pointers
    • Representation and nature of pointers, shown through comparing pointers with plain variables
    • Differences and similarities between pointers and plain variables
    • Relations between Pointers and Arrays
    • Nature of pointer offsets
    • Program reading practices
    • Top-down algorithm design practices
    • Debugging techniques of pointers
    Learning objectives
    • Understand the concept of pointers
    • Understand relations between pointers, arrays, and strings
    • Know how to use pointers to reference variables and arrays
    • Can use string arrays through pointers
    • Can design algorithms using the top-down stepwise refinement approach

    2.1  Concept of pointers

    2.1.1  Reference by name and reference by address

    We shall explain these concepts through real-life examples.
    Case study 1 Setting destination in a navigation system
    Postmen nowadays often use navigation systems to find their destination when delivering to a new location. To set the destination in a navigation system, one can input either the address or name of the location. For example, “Xidian University North Campus” refers to the location by name, while “2 South Taibai Road, Yanta District” refers to the same location by address, as shown in Figure 2.1 .
    To sum up, we can reference an object that has a location attributing either by name or by address.
    Case study 2 Classroom questioning and homework assignment
    Teachers often ask students questions in class. He/she may ask “the second student in the third row” to answer the question when he/she does not know the name of the student. In this case, the student’s name is a “reference by name,” while the student’s seat is a “reference by address.” When assigning homework, a teacher may use the following statements: “questions 6 and 8 of chapter 3” or “question 6 and 8 on page 126.” The chapter here is a “reference by name,” while the page number is a “reference by address,” as shown in Figure 2.2
  • Modern C++: Efficient and Scalable Application Development
    eBook - ePub

    Modern C++: Efficient and Scalable Application Development

    Leverage the modern features of C++ to overcome difficulties in various stages of application development

    • Richard Grimes, Marius Bancila(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)

    Working with Memory, Arrays, and Pointers

    C++ allows you to have direct access to memory through pointers. This gives you a lot of flexibility, and potentially it allows you to improve the performance of your code by eliminating some unnecessary copying of data. However, it also provides an extra source of errors; some can be fatal for your application or worse (yes, worse than fatal!) because poor use of memory buffers can open security holes in your code that can allow malware to take over the machine. Clearly pointers are an important aspect of C++.
    In this chapter, you'll see how to declare pointers and initialize them to memory locations, how to allocate memory on the stack and, C++ free store, and how to use C++ arrays.
    Passage contains an image

    Using memory in C++

    C++ uses the same syntax as C to declare pointer variables and assign them to memory addresses, and it has C-like pointer arithmetic. Like C, C++ also allows you to allocate memory on the stack, so there is automatic memory cleanup when the stack frame is destroyed, and dynamic allocation (on the C++ free store) where the programmer has the responsibility to release memory. This section will cover these concepts.
    Passage contains an image

    Using C++ pointer syntax

    The syntax to access memory in C++ is straightforward. The & operator returns the address of an object. That object can be a variable, a built-in type or the instance of a custom type, or even a function (function pointers will be covered in the next chapter). The address is assigned a typed pointer variable or a void* pointer. A void* pointer should be treated as merely storage for the memory address because you cannot access data and you cannot perform pointer arithmetic (that is, manipulate the pointer value using arithmetic operators) on a void* pointer. Pointer variables are usually declared using a type and the * symbol. For example:
    int i = 42; int *pi = &i;
    In this code, the variable i is an integer, and the compiler and linker will determine where this variable will be allocated. Usually, a variable in a function will be on a stack frame, as described in a later section. At runtime, the stack will be created (essentially a chunk of memory will be allocated) and space will be reserved in the stack memory for the variable i. The program then puts a value (42) in that memory. Next, the address of the memory allocated for the variable i is placed in the variable pi. The memory usage of the previous code is illustrated in the following diagram:
  • C++ for Financial Mathematics
    Arrays are only of interest if you know the size of your arrays when your code is compiled. For example, when working with 3D computer graphics, arrays of length 3 can be useful.
    Tip: Don’t use arrays Vectors do everything you want to do with arrays and much more.

    11.2   Pointers

    11.2.1   new and delete
    Because arrays are not flexible enough, the C language also contains the concept of a pointer. This allows a C programmer to work with sequences of data of varying lengths.
        int n = 5;    int * myArray = new int [n];    for (int i=0; i<n; i++) {        cout <<" Entry " <<i<<"=";        cout << myArray [i];        cout << "\n";    }    delete [] myArray ;
    The code above uses the new ...[] operator to allocate a chunk of memory. In this case we are creating a sequence of int data types in memory, but you could use other data types instead.
    The good news is that you can choose the size of the chunk of memory at run time. Unlike with an array, you don’t have to choose the size in advance when you write your program.
    The downside of using new [] is that the memory will not be automatically deleted when the variable goes out of scope (see Section 4.7 for the meaning of the word scope). You must use delete [] to free the memory created with the new[] operator. This is good and bad. With arrays we couldn’t return arrays because the memory was deleted automatically, but on the other hand we didn’t have to remember to call delete[] . With memory created using new[] we have to remember to delete the memory by hand, but you can safely return the data.
    The value returned by new int[n] is called a pointer . It has type int* which means “a pointer to an int ”. In actual fact the array discussed in the previous section was of type int* too. It’s just that the notation for arrays in C hides the fact that an array-valued variable is just a pointer to a memory location. All that the int* myArray contains is the memory address where the array starts. As a result, we have to remember ourselves that the block of memory is of length n
  • Introduction to Windows® and Graphics Programming with Visual C++®
    • 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
  • Ivor Horton's Beginning Visual C++ 2008
    • Ivor Horton(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    A*B for instance, there's no meaningful interpretation of this expression for anything other than a multiply operation.
    Why Use Pointers?
    A question that usually springs to mind at this point is, “Why use pointers at all?” After all, taking the address of a variable you already know and sticking it in a pointer so that you can dereference it seems like an overhead you can do without. There are several reasons why pointers are important.
    As you will see shortly, you can use pointer notation to operate on data stored in an array, which often executes faster than if you use array notation. Also, when you get to define your own functions later in the book, you will see that pointers are used extensively for enabling access within a function to large blocks of data, such as arrays, that are defined outside the function. Most importantly, however, you will also see later that you can allocate space for variables dynamically, that is, during program execution. This sort of capability allows your program to adjust its use of memory depending on the input to the program. Because you don't know in advance how many variables you are going to create dynamically, a primary way you have for doing this is by using pointers—so make sure you get the hang of this bit.
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.