Computer Science

Pointers in C

Pointers in C are variables that store the memory addresses of other variables. They allow for dynamic memory allocation and manipulation of data structures. Pointers are a powerful feature of the C programming language, but they require careful management to avoid errors and memory leaks.

Written by Perlego with AI-assistance

11 Key excerpts on "Pointers in C"

  • Book cover image for: Learn C Programming
    eBook - ePub

    Learn C Programming

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

    Using Pointers
    A pointer is a variable that holds a value that is the location (or memory address) of another value. The pointer type not only identifies the variable identifier as a pointer but also specifies what kind of value will be accessed at the location held by the pointer.
    It is essential to learn how to verbally differentiate the address of notation (a pointer value) versus the target of notation (the value found at the address that the pointer points to). In this chapter, we will strive to demystify C pointers.
    Learning how to properly use pointers expands both the expressiveness of C programs as well as the range of problems that can be solved. The following topics will be covered in this chapter:
    • Dispelling some myths and addressing some truths about C pointers
    • Understanding where values are stored and how they are accessed
    • Declaring pointers and naming them appropriately
    • Understanding the NULL pointer andvoid*
    • Pointer arithmetic
    • Accessing pointers and their targets
    • Comparing pointers
    • Talking and thinking about pointers correctly
    • Using pointers in function parameters
    • Accessing structures via pointers

    Technical requirements

    Continue to use the tools you chose from theTechnical 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 .

    Addressing pointers – the boogeyman of C programming

    Before we begin our understanding of declaring, initializing, and using pointers, we must address some common misconceptions and unavoidable truths about C pointers.
    C pointers are often considered one of the most troublesome concepts in C, so much so that many modern languages claim to have improved on C by removing pointers altogether. This is unfortunate. In many cases, this limits the language's power and expressiveness. Other languages still have pointers but severely restrict how they may be used.
    Pointers in C are one of its most powerful features. With great power comes great responsibility. That responsibility is nothing more than knowing how to correctly and appropriately use the power that is given. This responsibility also involves knowing when not to use that power and to understand its limits.
  • Book cover image for: Learn C Programming
    Chapter 13 : Using Pointers
    A pointer is a variable that holds a value; that value is the location (or memory address) of another value. The pointer data type has two important roles. First, it identifies the variable identifier as a pointer. Second, it specifies the kind of value that will be accessed at the location held by the pointer.
    It is essential to learn how to verbally differentiate the address of  notation (a pointer value) and the target of notation (the value found at the address that the pointer points to). In this chapter, we will strive to demystify C pointers.
    Learning how to properly use pointers expands both the expressiveness of C programs, as well as the range of problems that can be solved. The following topics will be covered in this chapter:
    • Dispelling some myths and addressing some truths about C pointers
    • Understanding where values are stored and how they are accessed
    • Declaring pointers and naming them appropriately
    • Using pointer arithmetic
    • Accessing pointers and their targets
    • Understanding the NULL  pointer and void*
    • Comparing pointers
    • Talking and thinking about pointers correctly
    • Using pointers in function parameters
    • Accessing structures via pointers

    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/Chapter13 .

    Addressing pointers – the boogeyman of C programming

    Before we begin our understanding of declaring, initializing, and using pointers, we must address some common misconceptions and unavoidable truths about C pointers.
    C pointers are often considered one of the most troublesome concepts in C, so much so that many modern languages claim to have improved on C by removing pointers altogether. This is unfortunate. In many cases, this limits the language's power and expressiveness. Other languages still have pointers but severely restrict how they may be used.
  • Book cover image for: 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.
  • Book cover image for: C Programming Pocket Primer
    5
    WORKING WITH Pointers in C
    T his chapter introduces pointers, which are often misunderstood and can be intimidating because of the conflicting and inaccurate explanation that you can find on the Internet.
    Languages like Java have removed pointers entirely because of their complexity, and C requires that a block of code be marked unsafe in order to access pointers. On the other hand, pointers are used extensively in C, so a good foundation is required in order to become an effective C programmer.
    The first part of this chapter introduces you to the concept of a pointer in C, along with examples of pointers to numbers, arrays, and strings. This section also contains C programs that use pointers to split a string and for loops that use pointers to find the divisors of a number.
    The second part of this chapter defines pointers to arrays of numbers as well as pointers to functions. You will learn how to use pointers to reverse a string, find uppercase and lowercase letters, how to remove whitespaces from a string, and how to count words in a line of text. The final section of this chapter contains C programs that illustrate how to define pointers to functions, function pointers as arguments, and how to define pointers to pointers.
    Now let’s start with a brief introduction about pointers and pointer declarations, as well as the address of a variable, dereferencing pointers, and using pointer arithmetic. As you will see, pointer-based arithmetic emulates array indexing and the two views of an array as an indexed data structure or as a buffer with pointer arithmetic are crucial to the development and understanding of why C pointers work in the ways that they do.
    WHAT ARE POINTERS?
     
    A variable declared with a “pointer” data type contains a memory address indicating where the actual data is located. With pointer data types it is common to say that the pointer variable “points to” the actual data rather than talking about a memory address. Here are some examples of data that a pointer “points to:”
  • Book cover image for: A Short Course in Computational Science and Engineering
    eBook - PDF

    A Short Course in Computational Science and Engineering

    C++, Java and Octave Numerical Programming with Free Software Tools

    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.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program Design

    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.
  • Book cover image for: Big C++
    eBook - PDF

    Big C++

    Late Objects

    • Cay S. Horstmann(Author)
    • 2017(Publication Date)
    • Wiley
      (Publisher)
    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. With a pointer, the loca- tion can vary. This capability has many useful applications. Pointers can be used to share values among different parts of a program. Pointers allow allocation of values on demand. Furthermore, as you will see in Chapter 10, pointers are necessary for implementing programs that manipulate objects of multiple related types. In the first half of this chapter, you will learn how to define pointers and access the values to which they point. 7.1.1 Defining Pointers Consider a person who wants a program for making bank deposits and withdrawals, but who may not always use the same bank account. By using a pointer, it is pos- sible to switch to a different account without modifying the code for deposits and withdrawals. Let’s start with a variable for storing an account balance: double harrys_account = 0; Now suppose that we want to write an algorithm that manipulates a bank account, but we anticipate that we may sometimes want to use harrys_account, sometimes another account. Using a pointer gives us that flexibility. A pointer tells you where a value is located, not what the value is. Like a pointer that points to different locations on a blackboard, a C++ pointer can point to different memory locations. © Alexey Chuvarkov/iStockphoto. 7.1 Defining and Using Pointers 225 2 1 harrys_account = account_pointer = 20300 0 20300 harrys_account = account_pointer = joint_account = 0 20312 0 20300 20312 Point to memory at given address Point to memory at new address double* account_pointer = &harrys_account account_pointer = &joint_account Figure 1 Pointers and Values in Memory Here is the definition of a pointer variable.
  • Book cover image for: C++ for Financial Mathematics
    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
  • Book cover image for: Mastering C Pointers
    eBook - PDF

    Mastering C Pointers

    Tools for Programming Power

    • Robert J. Traister(Author)
    • 2014(Publication Date)
    • Academic Press
      (Publisher)
    Chapter 8 Pointers and Functions While pointers are useful, powerful, and indispensable throughout all phases of C language programming, their capabilities yield high-powered program performance especially when dealing with programmed functions. We already know that arguments are passed to and from func-tions by value. It is not possible to change the value of a calling program variable within a function . . . unless we have the address of a variable in the calling program. C language functions can return values that can be, in turn, assigned to variables within the calling program, but through pointer operations, we can write specialized functions that will return a value to the calling program and change the values in other variables whose memory addresses are handed to the func-tion. In this manner, it is possible to write a function that, figur-atively, returns many values in a single operation. Again, the direct programming of pointers is what gives C lan-guage its power, expressiveness, and authority. It is also the pointer that has vaulted C language to the top of the list of languages most desirable for software development. The following program incorporates a special function to return 123 124 Chapter 8 the square of a value passed to it. This is a useless function for any but tutorial purposes, but as the discussion continues other exam-ples will be provided that will provide some practical application tools. The program follows: ma i n( ) { i nt x 7 y ; x = 1 2 ; y - 7 ; x = square(x); y = square(y); printf(%d %dn n , x, y); } i nt square(a) int a ; i return(a * a); } The squareO function is passed a value from the calling program. This value is assigned to a , a variable that is internal to the func-tion. The function return value is a * a , or the square of the passed value. This program will display the values: 144 49 on the monitor screen.
  • Book cover image for: Basic Computation and Programming with C
    Pointer 405 When an array is passed to a function, it always follows the call by reference mechanism. Array of pointers to string is much better than 2D character array to store multiple string of varying length. In 2D character array, there is a lot of wastage of memory. Void pointer is a special type of pointer that can point to a variable of any data type. Always initialize the pointer variables before access it. Initializing Pointer Variable to NULL Value means the pointer is not pointing to anywhere. Using pointer variable we can allocate memory dynamically. Function pointer holds the address of a function. R EVIEW E XERCISES 1. What is a pointer variable? How is the pointer initialized? 2. What do you mean by NULL pointer? 3. What are the different characteristics of a pointer? 4. What are the advantages of pointer? 5. “Pass by address refers to the address of a variable passed as an argument to the called function.” Justify the statement. 6. What is meant by dynamic memory allocation? 7. Are the expressions *ptr++ and ++*ptr same? Explain. 8. What do you understand by pointer to pointer? 9. Differentiate between malloc ( ) and calloc ( ). 10. What are call by value and call by reference? Explain with examples. 11. Write a function to swap the value of 2 variables without using any additional variable. The change should be permanent. 12. What is the relationship between an array name and pointer? 13. What is the difference between array of pointers and pointer to an array? 14. What is special about void pointer and what are the advantage and disadvantage of using void pointer? 15. How can the indirection operation (*) be used to access multidimensional array element? 16. What are the operations permissible on pointers? 17. Using pointer write a program to find out length of the given string without using strlen ( ) function.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    Program Design Including Data Structures

    All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 836 | Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists The statement p = q; copies the value of q into p . After this statement executes, both p and q point to the same memory location. Any changes made to *p automatically change the value of *q , and vice versa. Two pointer variables of the same type can be compared for equality, and so on. The expression p == q evaluates to true if p and q have the same value—that is, if they point to the same memory location. Similarly, the expression p != q evaluates to true if p and q point to different memory locations. Integer values can be added and subtracted from a pointer variable. The value of one pointer variable can be subtracted from another pointer variable. The arithmetic operations that are allowed differ from the arithmetic operations on numbers. First, let us use the following statements to explain the increment and decrement opera-tions on pointer variables: int *p; double *q; char *chPtr; studentType *stdPtr; //studentType is as defined before Recall that the size of the memory allocated for an int variable is 4 bytes, a double variable is 8 bytes, and a char variable is 1 byte. The memory allocated for a variable of type studentType is then 40 bytes. The statement p++; or p = p + 1; increments the value of p by 4 bytes because p is a pointer of type int . Similarly, the statements q++; chPtr++; increment the value of q by 8 bytes and the value of chPtr by 1 byte, respectively. 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.
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.