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

6 Key excerpts on "Pointers in C"

  • 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.
  • 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.
  • 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.
  • Modern C++: Efficient and Scalable Application Development
    No longer available

    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 All-in-One Desk Reference For Dummies
    • Dan Gookin(Author)
    • 2011(Publication Date)
    • For Dummies
      (Publisher)
    pointer .

    The simple definition of a pointer

    A pointer is a variable that holds a memory address. Although that may be fun enough, the pointer variable is also custom designed to manipulate values stored at those memory addresses.
    At first scare, pointers may seem silly. Why bother with pointers and memory locations when a variable’s value can be affected with a simple statement that even nonprogrammers can easily understand:
    a = b;
    But, pointers can do more than just change values. Because they manipulate memory directly, they give you a power that other programming languages lack. This ability takes some time to understand — and it’s important not to get ahead of yourself — so this book uncovers pointer details one step at a time.

    A boring program that’s suitable as an example

    You never know when the United States may suddenly convert to the metric system. My guess: never. If we ever succumb to world pressure, you have this program ready to help you make the switch:
    #include <stdio.h>
    #define KPM 1.609344
    int main()
    {
        float miles,kilometers;
        printf(“Enter a value in miles:”);
        scanf(“%f”,&miles);
        kilometers = miles*KPM;
        printf(“%.2f miles works out to %.2f kilometers.\n”, miles,kilometers);
        return(0);
    }
    Save the dopey thing to disk as METRIC.C. Compile and run.
    Enter a value in miles:
    Try to impress your metric-literate friends by telling them how long your commute is every day. Suppose that you trek 81/2 miles every day. Type 8.5 and press the Enter key:
    8.50 miles works out to 13.68 kilometers.
    Wow. Much impressive. Put this program on the back burner for later.

    Making Mr. Pointer

    In the final incarnation of ODDLITL.C (earlier in this chapter), you use the & operator to divine the location in memory for a slew of variables. The & produces an immediate value, however, displayed by using printf() ’s %p
  • 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.