Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

Relationship Between Arrays and Pointers

C Pass Addresses and Pointers

C structs and Pointers

  • Access Array Elements Using Pointer

C Dynamic Memory Allocation

  • C Array and Pointer Examples

Pointers are powerful features of C and C++ programming. Before we learn pointers, let's learn about addresses in C programming.

  • Address in C

If you have a variable var in your program, &var will give you its address in the memory.

We have used address numerous times while using the scanf() function.

Here, the value entered by the user is stored in the address of var variable. Let's take a working example.

Note: You will probably get a different address when you run the above code.

Pointers (pointer variables) are special variables that are used to store addresses rather than values.

Pointer Syntax

Here is how we can declare pointers.

Here, we have declared a pointer p of int type.

You can also declare pointers in these ways.

Let's take another example of declaring pointers.

Here, we have declared a pointer p1 and a normal variable p2 .

  • Assigning addresses to Pointers

Let's take an example.

Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.

Get Value of Thing Pointed by Pointers

To get the value of the thing pointed by the pointers, we use the * operator. For example:

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc .

Note: In the above example, pc is a pointer, not *pc . You cannot and should not do something like *pc = &c ;

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.

  • Changing Value Pointed by Pointers

We have assigned the address of c to the pc pointer.

Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Let's take another example.

Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is the same, c will be equal to 1.

Let's take one more example.

Initially, the address of c is assigned to the pc pointer using pc = &c; . Since c is 5, *pc gives us 5.

Then, the address of d is assigned to the pc pointer using pc = &d; . Since d is -15, *pc gives us -15.

  • Example: Working of Pointers

Let's take a working example.

Explanation of the program

A pointer variable and a normal variable is created.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c . Then,

Here's an example of pointer syntax beginners often find confusing.

Why didn't we get an error when using int *p = &c; ?

It's because

is equivalent to

In both cases, we are creating a pointer p (not *p ) and assigning &c to it.

To avoid this confusion, we can use the statement like this:

Now you know what pointers are, you will learn how pointers are related to arrays in the next tutorial.

Table of Contents

  • What is a pointer?
  • Common Mistakes

Sorry about that.

Related Tutorials

Codeforwin

Pointers in C – Declare, initialize and use

Pointers are the heart of C programming. It is the most distinct feature of C, which provides power and flexibility to C. Pointers separates C from other programming languages.

C programmers make extensive use of pointers, because of their numerous benefits. Below are some advantages of pointers.

  • Pointers are more efficient in handling arrays and structures.
  • Pointers are used to return multiple values from a function.
  • We use pointers to get reference of a variable or function.
  • Pointer allows dynamic memory allocation (creation of variables at runtime) in C. Which undoubtedly is the biggest advantage of pointers.
  • Pointers increases execution speed of program.

Pointers are closely related to low level memory operations. Hence, let us first understand memory in contrast to C programming.

Understanding memory

Computer memory ( RAM ) is a collection of contiguous block of bytes. Where individual block is called as cell (memory cell). Each cell has a unique numeric address (also known as physical memory address) associated with it. These addresses starts from zero and runs up to maximum memory size (in bytes).

For example, memory location of a 64KB RAM starts from 0 and ends to 65536 (or 0x10000) bytes.

Memory representation

Before I formally introduce pointers let us first see what happens during a variable definition. Consider the statement int num = 10;

  • For the above statement, the C compiler allocates memory capable to store an integer. Let say memory is allocated at address 0x1200 .
  • After memory allocation , the C compiler defines a label (variable name) to access the memory location. The label is mapped to the allocated memory.
  • Finally, the constant 10 is stored at 0x1200 . Whenever you refer num inside your program, internally C refers to the memory location of num .

What is a pointer?

A pointer is a variable that stores memory address. If it is a variable, it must have a valid C data type . Yes, every pointer variable has a data type associated with it. Which means an integer pointer can hold only integer variable addresses.

Note: We never say pointer stores or holds a memory location. Instead, we say pointer points to a memory location. So from now always use the language pointer points to a memory location.

Reference operator &

Because we are dealing with memory addresses, we must know how to get memory address of a variable. We use unary & (reference of) operator to get memory address of a variable. Reference operator is also known as address of operator .

Read more about operators in C programming .

Syntax to use reference of operator

Example program to use reference operator.

Note: Output of above program may vary on your machine.

Dereference operator *

Once you have a memory address, you must be willing to get value stored at that memory address, for that we need to dereference the memory address.

Dereferencing is the process of retrieving value at memory location pointed by a pointer. We use unary * dereference operator to get value pointed by a memory address. Dereference operator is also known as indirection operator .

Syntax to use dereference operator

Example program to use dereference operator, how to declare pointer variable.

Once you got basics of memory addresses, reference and dereference operator. Let us declare our first pointer variable.

Pointer variable declaration follows almost similar syntax as of normal variable.

Syntax to declare pointer variable

  • data-type is a valid C data type .
  • * symbol specifies it is a pointer variable. You must prefix * before variable name to declare it as a pointer.
  • pointer-variable-name is a valid C identifier i.e. the name of pointer variable.

Example to declare pointer variable

In above example I declared an integer pointer.

How to initialize pointer variable

There are two ways to initialize a pointer variable. You can use reference operator & to get memory location of a variable or you can also directly assign one pointer variable to other pointer variable.

Examples to initialize pointer variable

How pointers are stored in memory.

You got a basic picture of pointer working. Let us take a closer look on how pointer variables are stored in memory. Consider the following statements

Pointer memory representation

Example program to use pointers

Write a C program to demonstrate the use of pointers in C programming.

Note: %x format specifier is used to print hexadecimal representation of a decimal .

Output –

Note: Output of above program may differ on your system.

Working of above program

  • int *ptr = # declares an integer pointer that points at num .
  • The first two printf() in line 12 and 13 are straightforward. First prints value of num and other prints memory address of num .
  • printf("Value of ptr = %x \n", ptr); prints the value stored at ptr i.e. memory address of num . Hence, the statement prints memory address of num .

Don’t confuse with address of ptr and address pointed by ptr . First ptr is a variable so it will have a memory address which is retrieved using &ptr . And since it is a pointer variable hence it stores memory address which is retrieved using ptr .

  • printf("Value pointed by ptr = %d \n\n", *ptr); , here * dereferences value pointed by ptr and prints the value at memory location pointed by ptr .
  • Next, we made some changes to num i.e. num=10 . After changes printf("Value of num = %d \n", num); prints 10.
  • Since we made changes to our original variable num , hence changes are reflected back to pointer that points to the num . *ptr in line 23, dereferences value pointed by ptr i.e. 10.
  • *ptr = 100; says assign 100 to memory location pointed by ptr . Which means, assign 100 to num indirectly.
  • Since, we again modified the value of num using *ptr = 100 . Hence, num and *ptr in line 28 and 29 will evaluate to 100.

Recommended examples to practice

  • Program to demonstrate use of pointers.
  • Program to add two numbers using pointers.
  • Program to swap two numbers using pointers.
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Related Articles

  • Solve Coding Problems
  • Pointer Arithmetics in C with Examples
  • Applications of Pointers in C
  • Passing Pointers to Functions in C
  • C - Pointer to Pointer (Double Pointer)
  • Chain of Pointers in C with Examples
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • NULL Pointer in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

In this article, we will discuss C pointers in detail, their types, uses, advantages, and disadvantages with examples.

What is a Pointer in C?

A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers.

As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. This size of pointers in C only depends on the system architecture.

Syntax of C Pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.

  • ptr is the name of the pointer.
  • datatype is the type of data it is pointing to.

The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.

How to Use Pointers?

The use of pointers in C can be divided into three steps:

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name.

The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.

2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time.

Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing

Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.

dereferencing a pointer in c

Dereferencing a Pointer in C

C Pointer Example

Types of pointers in c.

Pointers in C can be classified into many different types based on the parameter on which we are defining their types. If we consider the type of variable stored in the memory location pointed by the pointer, then the pointers can be classified into the following types:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values.

These pointers are pronounced as Pointer to Integer.

Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such as arrays and user-defined data types such as structures.

2. Array Pointer

Pointers and Array are closely related to each other. Even the array name is the pointer to its first element. They are also known as Pointer to Arrays . We can create a pointer to an array using the given syntax.

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

3. Structure Pointer

The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be declared in the same way as we declare the other primitive data types.

In C, structure pointers are used in data structures such as linked lists, trees, etc.

4. Function Pointers

Function pointers point to the functions. They are different from the rest of the pointers in the sense that instead of pointing to the data, they point to the code. Let’s consider a function prototype – int func (int, char) , the function pointer for this function will be

Note: The syntax of the function pointers changes according to the function prototype.

5. Double Pointers

In C language, we can define a pointer that stores the memory address of another pointer. Such pointers are called double-pointers or pointers-to-pointer . Instead of pointing to a data value, they point to another pointer.

Dereferencing Double Pointer

Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4, ******ptr5 and so on.

6. NULL Pointer

The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.

It is said to be good practice to assign NULL to the pointers currently not in use.

7. Void Pointer

The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. They are also called generic pointers as they can point to any type and can be typecasted to any type.

One of the main properties of void pointers is that they cannot be dereferenced.

8. Wild Pointers

The Wild Pointers are pointers that have not been initialized with something yet. These types of C-pointers can cause problems in our programs and can eventually cause them to crash.

9. Constant Pointers

In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address.

10. Pointer to Constant

The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant.

Other Types of Pointers in C:

There are also the following types of pointers available to use in C apart from those specified above:

  • Far pointer : A far pointer is typically 32-bit that can access memory outside the current segment.
  • Dangling pointer : A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.
  • Huge pointer : A huge pointer is 32-bit long containing segment address and offset address.
  • Complex pointer: Pointers with multiple levels of indirection.
  • Near pointer : Near pointer is used to store 16-bit addresses means within the current segment on a 16-bit machine.
  • Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as possible.
  • File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C

The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is 

  • 8 bytes for a 64-bit System
  • 4 bytes for a 32-bit System

The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types.

How to find the size of pointers in C?

We can find the size of pointers using the sizeof operator as shown in the following program:

Example: C Program to find the size of different pointer types.

As we can see, no matter what the type of pointer it is, the size of each and every pointer is the same.

Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic

The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers. These operations include:

  • Increment in a Pointer
  • Decrement in a Pointer
  • Addition of integer to a pointer
  • Subtraction of integer to a pointer
  • Subtracting two pointers of the same type
  • Comparison of pointers of the same type.
  • Assignment of pointers of the same type.

C Pointers and Arrays

In C programming language, pointers and arrays are closely related. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably.

If we assign this value to a non-constant pointer of the same type, then we can access the elements of the array using this pointer.

Example 1: Accessing Array Elements using Pointer with Array Subscript

relationship between array and pointer

Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.

Example 2: Accessing Array Elements using Pointer Arithmetic

accessing array elements using pointer arithmetic

This concept is not limited to the one-dimensional array, we can refer to a multidimensional array element as well using pointers.

To know more about pointers to an array, refer to this article – Pointer to an Array

Uses of Pointers in C

The C pointer is a very powerful tool that is widely used in C programming to perform various useful operations. It is used to achieve the following functionalities in C:

  • Pass Arguments by Reference
  • Accessing Array Elements
  • Return Multiple Values from Function
  • Dynamic Memory Allocation
  • Implementing Data Structures
  • In System-Level Programming where memory addresses are useful.
  • In locating the exact value at some memory location.
  • To avoid compiler confusion for the same variable name.
  • To use in Control Tables.

Advantages of Pointers

Following are the major advantages of pointers in C:

  • Pointers are used for dynamic memory allocation and deallocation.
  • An Array or a structure can be accessed efficiently with pointers
  • Pointers are useful for accessing memory locations.
  • Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
  • Pointers reduce the length of the program and its execution time as well.

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:

  • Memory corruption can occur if an incorrect value is provided to pointers.
  • Pointers are a little bit complex to understand.
  • Pointers are majorly responsible for memory leaks in C .
  • Pointers are comparatively slower than variables in C.
  • Uninitialized pointers might cause a segmentation fault.

In conclusion, pointers in C are very capable tools and provide C language with its distinguishing features, such as low-level memory access, referencing, etc. But as powerful as they are, they should be used with responsibility as they are one of the most vulnerable parts of the language.

FAQs on Pointers in C

Q1. define pointers..

Pointers are the variables that can store the memory address of another variable.

Q2. What is the difference between a constant pointer and a pointer to a constant?

A constant pointer points to the fixed memory location, i.e. we cannot change the memory address stored inside the constant pointer. On the other hand, the pointer to a constant point to the memory with a constant value.

Q3. What is pointer to pointer?

A pointer to a pointer (also known as a double pointer) stores the address of another pointer.

Q4. Does pointer size depends on its type?

No, the pointer size does not depend upon its type. It only depends on the operating system and CPU architecture.

Q5. What are the differences between an array and a pointer?

The following table list the differences between an array and a pointer : Pointer Array A pointer is a derived data type that can store the address of other variables. An array is a homogeneous collection of items of any type such as int, char, etc. Pointers are allocated at run time. Arrays are allocated at runtime. The pointer is a single variable. An array is a collection of variables of the same type. Dynamic in Nature Static in Nature.

Q6. Why do we need to specify the type in the pointer declaration?

Type specification in pointer declaration helps the compiler in dereferencing and pointer arithmetic operations.
  • Quiz on Pointer Basics
  • Quiz on Advanced Pointer

Please Login to comment...

  • Prasant Nair Cricket Research
  • SHUBHAMSINGH10
  • arorakashish0911
  • susobhanakhuli
  • varshneyapoorv11
  • kapilbaser44
  • mitalibhola94
  • kamleshjoshi18
  • abhishekcpp
  • tanishabutola04
  • shuklakindw4o

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

techieclues.com

  • TechieClues

Converting Int to Pointer in C

C

  • Programming

Join Techieclues community and access the complete membership experience.

Introduction:

C programming allows developers to perform intricate operations, one of which involves casting an integer to a pointer. This process can be complex, and it's crucial for a deep understanding of the language. In this blog, we will explore different methods of converting an integer to a pointer in C

Method 1: Explicit Casting

The first method involves the explicit casting of the integer to a pointer. In this case, we use the (int*) syntax to inform the compiler that we are intentionally converting an integer to a pointer. It's important to note that explicit casting should be approached with caution, as it may lead to undefined behavior if not done correctly.

Explicit casting is a common but risky approach. It directly tells the compiler to treat the integer as a pointer. However, if the integer doesn't represent a valid memory address or if the cast is not done correctly, it can lead to runtime errors or undefined behavior.

Method 2: Using intptr_t

The second method introduces a safer approach by utilizing the intptr_t type from the stdint.h header. This type is specifically designed to hold integers that can be converted to and from pointers without loss of data. By casting the integer to intptr_t and then converting it to a pointer, we aim for a more portable and reliable solution.

Using intptr_t provides a safer alternative. It ensures that the integer is first cast to a type designed to hold pointers safely. This method is generally more portable across different systems and compilers.

Method 3: Using Pointers Directly

The third method involves a more conventional approach, using pointers directly. Instead of explicitly casting the integer, we take its address using the & operator and assign it to a pointer variable. This method is straightforward and aligns with the fundamental principles of pointer usage in C.

Using pointers directly is a straightforward approach. It doesn't involve explicit casting, and it relies on the fundamental concept of pointers in C. The pointer, in this case, holds the address of the integer variable.

Conclusion:

In this blog, we have explored the various methods for converting an integer to a pointer in C, like explicit casting is a common practice, it introduces potential risks and may not be as portable. Using  intptr_t or working with pointers directly offers more robust and reliable solutions, aligning with the principles of C programming.

Related Post

  • Different Algorithm for String in Programming
  • Convert Int to String in C
  • Convert String to Int in C
  • Converting Double to Int in C
  • Converting Int to Double in C
  • Converting Char to Int in C
  • Convert Int to Char in C
  • Converting Float to Int in C
  • Converting Int to Float in C
  • Converting Hex to Decimal in C

ABOUT THE AUTHOR

https://www.techieclues.com/profile/mohanapriya-r

Comments (0)

c assign int to pointer

Latest Tutorials

C#

Latest Posts

  • Converting Base58 Encoded to String in PHP
  • Convert Array to HTML Table with Custom Classes in PHP
  • How to Generate a File Compression Program in Python?
  • Converting Queue to String in C++
  • Introduction to PNG to PDF Conversion with Python
  • Converting HTML Table with Custom Classes to Array in PHP
  • Converting Double to String in C
  • Converting a Single JPG Image to PDF Using Python
  • Hosting a Static Website with Azure Storage Service
  • How to Generate a Simple Paint Program in Python?

Popular Posts

  • Create a Simple CRUD Windows Application In C#
  • Build ASP.NET Core Web API with CRUD Operations Using Entity Framework Core
  • Currency Format In C#
  • How to Increase the Session Timeout in ASP.NET MVC Application
  • How to Add Elements To an Array in C#
  • Insert, Update and Delete Records (CRUD) in C# DataGridView
  • How to Upload and Download Files in ASP.NET Core
  • Simple CRUD Operation With Asp.Net Core and Angular - Part 1
  • CRUD Operations In Windows Application Using C# - Part 2
  • Top 50 SDLC Interview Questions and Answers (2024)

Sign in with TechieClues

DEV Community

DEV Community

AbdulKarim

Posted on Oct 29, 2023

How C-Pointers Works: A Step-by-Step Beginner's Tutorial

In this comprehensive C Pointers tutorial, my primary goal is to guide you through the fundamentals of C pointers from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • What is a Pointer?
  • How Data is Stored in Memory?
  • Storing Memory Addresses using Pointers

Accessing Data through Pointers

  • Pointer Arithmetic
  • Pointer to Pointer (Double Pointers)
  • Passing Pointers as Function Arguments

Arrays of Pointers

Null pointers, prerequisite:.

To grasp pointers effectively, you should be comfortable with basic C programming concepts, including variables, data types, functions, loops, and conditional statements. This familiarity with C programming forms the foundation for understanding how pointers work within the language. Once you have a solid grasp of these fundamental concepts, you can confidently delve into the intricacies of C pointers.

What is a pointer?

A pointer serves as a reference that holds the memory location of another variable. This memory address allows us to access the value stored at that location in the memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory

Pointers can be a challenging concept for beginners to grasp, but in this tutorial, I'll explain them using real-life analogies to make the concept clearer. However, Before delving into pointers and their workings, it's important to understand the concept of a memory address.

A memory address is a unique identifier that points to a specific location in a computer's memory. Think of it like a street address for data stored in your computer's RAM (Random Access Memory). Just as a street address tells you where a particular house is located in the physical world, a memory address tells the computer where a specific piece of information or data is stored in its memory.

Take a look at the image below for a better understanding:

Block of memory

In this illustration, each block represents one byte of memory. It's important to note that every byte of memory has a unique address. To make it easier to understand, I've represented the addresses in decimal notation, but computers actually store these addresses using hexadecimal values. Hexadecimal is a base-16 numbering system commonly used in computing to represent memory addresses and other low-level data. It's essential to be aware of this representation when working with memory-related concepts in computer programming

How data is stored in the memory:

Every piece of data in your computer, whether it's a number, a character, or a program instruction, is stored at a specific memory address. The amount of space reserved for each data type can vary, and it is typically measured in bytes (where 1 byte equals 8 bits, with each bit representing either 0 or 1). The specific sizes of data types also depend on the computer architecture you are using. For instance, on most 64-bit Linux machines, you'll find the following typical sizes for common data types: char = 1 byte int = 4 bytes float = 4 bytes double = 8 bytes These sizes define how much memory each data type occupies and are crucial for memory management and efficient data representation in computer systems.

You can use the sizeof operator to determine the size of data types on your computer. example:

In this example: sizeof(char) returns the size of the char data type in bytes. sizeof(int) returns the size of the int data type in bytes. sizeof(float) returns the size of the float data type in bytes. sizeof(double) returns the size of the double data type in bytes. When you run this code, it will print the sizes of these data types on your specific computer, allowing you to see the actual sizes used by your system.

When you declare a variable, the computer allocates a specific amount of memory space corresponding to the chosen data type. For instance, when you declare a variable of type char, the computer reserves 1 byte of memory because the size of the 'char' data type is conventionally 1 byte.

address of char n

In this example, we declare a variable n of type char without assigning it a specific value. The memory address allocated for the n variable is 106 . This address, 106 , is where the computer will store the char variable n, but since we haven't assigned it a value yet, the content of this memory location may initially contain an unpredictable or uninitialized value.

When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n. When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n.

address of cahr n = c

As mentioned earlier, a byte can only store numerical values. When we store the letter 'C' in a byte, the byte actually holds the ASCII code for 'C,' which is 67. In computer memory, characters are represented using their corresponding ASCII codes. So, in memory, the character 'C' is stored as the numerical value 67. Here's how it looks in memory

Ascii code of c

Since integers are typically stored within four bytes of memory, let's consider the same example with an int variable. In this scenario, the memory structure would appear as follows:

add. of int t

In this example, the memory address where the variable t is stored is 121. An int variable like “t” typically uses four consecutive memory addresses, such as 121, 122, 123, and 124. The starting address, in this case, 121, represents the location of the first byte of the int, and the subsequent addresses sequentially represent the following bytes that collectively store the complete int value.

If you want to know the memory address of a variable in a program, you can use the 'address of' unary operator, often denoted as the '&' operator. This operator allows you to access the specific memory location where a variable is stored.

When you run the following program on your computer: It will provide you with specific memory addresses for the variables c and n. However, each time you rerun the program, it might allocate new memory addresses for these variables. It's important to understand that while you can determine the memory address of a variable using the & operator, the exact memory location where a variable is stored is typically managed by the system and the compiler. As a programmer, you cannot directly control or assign a specific memory location for a variable. Instead, memory allocation and management are tasks handled by the system and the compiler.

Storing memory address using pointers

As mentioned earlier, a pointer is a variable that stores the memory address of another variable. This memory address allows us to access the value stored at that location in memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory.

Now, let's begin by declaring and initializing pointers. This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location.

Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, we've declared a pointer named ptr that can point to integers.

Memory of Declaring an integer pointer

The size of pointers on 64-bit systems is usually 8 bytes (64 bits). To determine the pointer size on your system, you can use the sizeof operator:

Initializing Pointers: Once you've declared a pointer, you typically initialize it with the memory address it should point to. Once again, To obtain the memory address of a variable, you can employ the address-of operator (&). For instance:

In this program:

We declare an integer variable x and initialize it with the value 10. This line creates a variable x in memory and assigns the value 10 to it.

ptr

We declare an integer pointer ptr using the int *ptr syntax. This line tells the compiler that ptr will be used to store the memory address of an integer variable.

pointrt to ptr

We initialize the pointer ptr with the memory address of the variable x . This is achieved with the line ptr = &x; . The & operator retrieves the memory address of x, and this address is stored in the pointer ptr .

address of variable x

Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values. To get the actual value (data) stored at that memory address, you need to dereference the pointer.

Dereferencing is done using the asterisk (*) operator. Here's an example:

It looks like this in the memory: int x = 10; variable 'x' stores the value 10:

var X

int *ptr = &x; Now, the pointer 'ptr' point to the address of 'x':

Pointer to X

int value = *ptr; Dereference 'ptr' to get the value stored at the address it points to:

pointer value is 10

Reading and Modifying Data: Pointers allow you to not only read but also modify data indirectly:

Note: The asterisk is a versatile symbol with different meanings depending on where it's used in your C program, for example: Declaration: When used during variable declaration, the asterisk (*) indicates that a variable is a pointer to a specific data type. For example: int *ptr; declares 'ptr' as a pointer to an integer.

Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to.

Pointer Arithmetic:

Pointer arithmetic is the practice of performing mathematical operations on pointers in C. This allows you to navigate through arrays, structures, and dynamically allocated memory. You can increment or decrement pointers, add or subtract integers from them, and compare them. It's a powerful tool for efficient data manipulation, but it should be used carefully to avoid memory-related issues.

Incrementing a Pointer:

Now, this program is how it looks in the memory: int arr[4] = {10, 20, 30, 40};

int arr

This behavior is a key aspect of pointer arithmetic. When you add an integer to a pointer, it moves to the memory location of the element at the specified index, allowing you to efficiently access and manipulate elements within the array. It's worth noting that you can use pointer arithmetic to access elements in any position within the array, making it a powerful technique for working with arrays of data. Now, let's print the memory addresses of the elements in the array from our previous program.

If you observe the last two digits of the first address is 40, and the second one is 44. You might be wondering why it's not 40 and 41. This is because we're working with an integer array, and in most systems, the size of an int data type is 4 bytes. Therefore, the addresses are incremented in steps of 4. The first address shows 40, the second 44, and the third one 48

Decrementing a Pointer Decrement (--) a pointer variable, which makes it point to the previous element in an array. For example, ptr-- moves it to the previous one. For example:

Explanation:

We have an integer array arr with 5 elements, and we initialize a pointer ptr to point to the fourth element (value 40) using &arr[3].

Then, we decrement the pointer ptr by one with the statement ptr--. This moves the pointer to the previous memory location, which now points to the third element (value 30).

Finally, we print the value pointed to by the decremented pointer using *ptr, which gives us the value 30.

In this program, we demonstrate how decrementing a pointer moves it to the previous memory location in the array, allowing you to access and manipulate the previous element.

Pointer to pointer

Pointers to pointers, or double pointers, are variables that store the address of another pointer. In essence, they add another level of indirection. These are commonly used when you need to modify the pointer itself or work with multi-dimensional arrays.

To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example:

In this example, ptr2 is a pointer to a pointer. It points to the memory location where the address of x is stored (which is ptr1 ).

pointer to poiter

The below program will show you how to print the value of x through pointer to pointer

In this program, we first explain that it prints the value of x using a regular variable, a pointer, and a pointer to a pointer. We then print the memory addresses of x , ptr1 , and ptr2 .

Passing Pointers as Function Arguments:

In C, you can pass pointers as function arguments. This allows you to manipulate the original data directly, as opposed to working with a copy of the data, as you would with regular variables. Here's how it works:

How to Declare and Define Functions that Take Pointer Arguments: In your function declaration and definition, you specify that you're passing a pointer by using the * operator after the data type. For example:

In the above function, we declare ptr as a pointer to an integer. This means it can store the memory address of an integer variable.

Why Would You Pass Pointers to Functions?

Passing pointers to functions allows you to:

  • Modify the original data directly within the function.
  • Avoid making a copy of the data, which can be more memory-efficient.
  • Share data between different parts of your program efficiently.

This concept is especially important when working with large data structures or when you need to return multiple values from a function.

Call by Value vs. Call by Reference:

Understanding how data is passed to functions is crucial when working with pointers. there are two common ways that data can be passed to functions: call by value and call by reference.

Call by Value:

When you pass data by value, a copy of the original data is created inside the function. Any modifications to this copy do not affect the original data outside of the function. This is the default behavior for most data types when you don't use pointers.

Call by Reference (Using Pointers):

When you pass data by reference, you're actually passing a pointer to the original data's memory location. This means any changes made within the function will directly affect the original data outside the function. This is achieved by passing pointers as function arguments, making it call by reference. Using pointers as function arguments allows you to achieve call by reference behavior, which is particularly useful when you want to modify the original data inside a function and have those changes reflected outside the function.

Let's dive into some code examples to illustrate how pointers work as function arguments. We'll start with a simple example to demonstrate passing a pointer to a function and modifying the original data.

Consider this example:

In this code, we define a function modifyValue that takes a pointer to an integer. We pass the address of the variable num to this function, and it doubles the value stored in num directly.

This is a simple demonstration of passing a pointer to modify a variable's value. Pointers allow you to work with the original data efficiently.

An array of pointers is essentially an array where each element is a pointer. These pointers can point to different data types (int, char, etc.), providing flexibility and efficiency in managing memory.

How to Declare an Array of Pointers? To declare an array of pointers, you specify the type of data the pointers will point to, followed by square brackets to indicate it's an array, and then the variable name. For example:

Initializing an Array of Pointers You can initialize an array of pointers to each element to point to a specific value, For example:

How to Access Elements Through an Array of Pointers? To access elements through an array of pointers, you can use the pointer notation. For example:

This program demonstrates how to access and print the values pointed to by the pointers in the array.

A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers.

Here's a code example that demonstrates the use of a NULL pointer:

In this example, we declare a pointer ptr and explicitly initialize it with the value NULL. We then use an if statement to check if the pointer is NULL. Since it is, the program will print "The pointer is NULL." This illustrates how NULL pointers are commonly used to check if a pointer has been initialized or assigned a valid memory address.

conclusion:

You've embarked on a comprehensive journey through the intricacies of C pointers. You've learned how pointers store memory addresses, enable data access, facilitate pointer arithmetic, and how they can be used with arrays and functions. Additionally, you've explored the significance of NULL pointers.

By completing this tutorial, you've equipped yourself with a robust understanding of pointers in C. You can now confidently navigate memory, manipulate data efficiently, and harness the power of pointers in your programming projects. These skills will be invaluable as you advance in your coding endeavors. Congratulations on your accomplishment, and keep coding with confidence!

Reference: C - Pointers - Tutorials Point

Pointers in C: A One-Stop Solution for Using C Pointers - simplilearn

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

imperiald profile image

  • Joined Jan 7, 2024

Love your way to write articles, could you add an article for, .o files, .h files, lists and makefile? Thank you in advance!

cocomelonjuice profile image

  • Joined Nov 4, 2023

Great post. Thank you so much for this.

koderkareem profile image

Thank you for your kind words! I'm thrilled to hear that you enjoyed the article. Your feedback means a lot to me. If you have any questions or if there's a specific topic you'd like to see in future posts, feel free to let me know. Thanks again for your support

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

dimuthnilanjana profile image

UI/UX for Beginners

Dimuth Nilanjana - Feb 14

devendra_2806 profile image

JavaScript Loops: A Beginner's Guide

Devendra Devendra - Feb 18

sre_panchanan profile image

OWASP API6:2023 Unrestricted Access to Sensitive Business Flows 🔐👤💔

Panchanan Panigrahi - Feb 14

digital_hub profile image

WordPress 6.5 Beta 1 is ready for download and testing!

hub - Feb 14

Once suspended, koderkareem will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, koderkareem will be able to comment and publish posts again.

Once unpublished, all posts by koderkareem will become hidden and only accessible to themselves.

If koderkareem is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to AbdulKarim.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag koderkareem:

koderkareem consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging koderkareem will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

C Programming/Pointers and arrays

A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location.

There are four fundamental things you need to know about pointers:

  • How to declare them (with the address operator ' & ': int *pointer = &variable; )
  • How to assign to them ( pointer = NULL; )
  • How to reference the value to which the pointer points (known as dereferencing , by using the dereferencing operator ' * ': value = *pointer; )
  • How they relate to arrays (the vast majority of arrays in C are simple lists, also called "1 dimensional arrays", but we will briefly cover multi-dimensional arrays with some pointers in a later chapter ).

Pointers can reference any data type, even functions. We'll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers.

  • 1 Declaring pointers
  • 2 Assigning values to pointers
  • 3 Pointer dereferencing
  • 4 Pointers and Arrays
  • 5 Pointers in Function Arguments
  • 6 Pointers and Text Strings
  • 7.1 Practical use of function pointers in C
  • 8 Examples of pointer constructs
  • 10 External Links

Declaring pointers [ edit | edit source ]

Consider the following snippet of code which declares two pointers:

Lines 1-4 define a structure . Line 8 declares a variable that points to an int , and line 9 declares a variable that points to something with structure MyStruct. So to declare a variable as something that points to some type, rather than contains some type, the asterisk ( * ) is placed before the variable name.

In the following, line 1 declares var1 as a pointer to a long and var2 as a long and not a pointer to a long. In line 2, p3 is declared as a pointer to a pointer to an int.

Pointer types are often used as parameters to function calls. The following shows how to declare a function which uses a pointer as an argument. Since C passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. More about pointers as function arguments later.

Assigning values to pointers [ edit | edit source ]

So far we've discussed how to declare pointers. The process of assigning values to pointers is next. To assign the address of a variable to a pointer, the & or 'address of' operator is used.

Here, pPointer will now reference myInt and pKeyboard will reference dvorak.

Pointers can also be assigned to reference dynamically allocated memory. The malloc() and calloc() functions are often used to do this.

The malloc function returns a pointer to dynamically allocated memory (or NULL if unsuccessful). The size of this memory will be appropriately sized to contain the MyStruct structure.

The following is an example showing one pointer being assigned to another and of a pointer being assigned a return value from a function.

When returning a pointer from a function, do not return a pointer that points to a value that is local to the function or that is a pointer to a function argument. Pointers to local variables become invalid when the function exits. In the above function, the value returned points to a static variable. Returning a pointer to dynamically allocated memory is also valid.

Pointer dereferencing [ edit | edit source ]

To access a value to which a pointer points, the * operator is used. Another operator, the -> operator is used in conjunction with pointers to structures. Here's a short example.

The expression bb->m_aNumber is entirely equivalent to (*bb).m_aNumber . They both access the m_aNumber element of the structure pointed to by bb . There is one more way of dereferencing a pointer, which will be discussed in the following section.

When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.

C is known for giving you just enough rope to hang yourself, and pointer dereferencing is a prime example. You are quite free to write code that accesses memory outside that which you have explicitly requested from the system. And many times, that memory may appear as available to your program due to the vagaries of system memory allocation. However, even if 99 executions allow your program to run without fault, that 100th execution may be the time when your "memory pilfering" is caught by the system and the program fails. Be careful to ensure that your pointer offsets are within the bounds of allocated memory!

The declaration void *somePointer; is used to declare a pointer of some nonspecified type. You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Pointer arithmetic is also not valid with void * pointers.

Pointers and Arrays [ edit | edit source ]

Up to now, we've carefully been avoiding discussing arrays in the context of pointers. The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:

  • A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array.
  • A pointer can be indexed like an array name.

The first case often is seen to occur when an array is passed as an argument to a function. The function declares the parameter as a pointer, but the actual argument may be the name of an array. The second case often occurs when accessing dynamically allocated memory.

Let's look at examples of each. In the following code, the call to calloc() effectively allocates an array of struct MyStruct items.

Pointers and array names can pretty much be used interchangeably; however, there are exceptions. You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array. In the function returnSameIfAnyEquals , you could however assign a new value to workingArray, as it is just a pointer to the first element of workingArray. It is also valid for a function to return a pointer to one of the array elements from an array passed as an argument to a function. A function should never return a pointer to a local variable, even though the compiler will probably not complain.

When declaring parameters to functions, declaring an array variable without a size is equivalent to declaring a pointer. Often this is done to emphasize the fact that the pointer variable will be used in a manner equivalent to an array.

Now we're ready to discuss pointer arithmetic. You can add and subtract integer values to/from pointers. If myArray is declared to be some type of array, the expression *(myArray+j) , where j is an integer, is equivalent to myArray[j] . For instance, in the above example where we had the expression secondArray[i].otherNumber , we could have written that as (*(secondArray+i)).otherNumber or more simply (secondArray+i)->otherNumber .

Note that for addition and subtraction of integers and pointers, the value of the pointer is not adjusted by the integer amount, but is adjusted by the amount multiplied by the size of the type to which the pointer refers in bytes. (For example, pointer + x can be thought of as pointer + (x * sizeof(*type)) .)

One pointer may also be subtracted from another, provided they point to elements of the same array (or the position just beyond the end of the array). If you have a pointer that points to an element of an array, the index of the element is the result when the array name is subtracted from the pointer. Here's an example.

You may be wondering how pointers and multidimensional arrays interact. Let's look at this a bit in detail. Suppose A is declared as a two dimensional array of floats ( float A[D1][D2]; ) and that pf is declared a pointer to a float. If pf is initialized to point to A[0][0], then *(pf+1) is equivalent to A[0][1] and *(pf+D2) is equivalent to A[1][0]. The elements of the array are stored in row-major order.

Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length. What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:

We also note here something curious about array indexing. Suppose myArray is an array and i is an integer value. The expression myArray[i] is equivalent to i[myArray] . The first is equivalent to *(myArray+i) , and the second is equivalent to *(i+myArray) . These turn out to be the same, since the addition is commutative.

Pointers can be used with pre-increment or post-decrement, which is sometimes done within a loop, as in the following example. The increment and decrement applies to the pointer, not to the object to which the pointer refers. In other words, *pArray++ is equivalent to *(pArray++) .

Pointers in Function Arguments [ edit | edit source ]

Often we need to invoke a function with an argument that is itself a pointer. In many instances, the variable is itself a parameter for the current function and may be a pointer to some type of structure. The ampersand ( & ) character is not needed in this circumstance to obtain a pointer value, as the variable is itself a pointer. In the example below, the variable pStruct , a pointer, is a parameter to function FunctTwo , and is passed as an argument to FunctOne .

The second parameter to FunctOne is an int. Since in function FunctTwo , mValue is a pointer to an int, the pointer must first be dereferenced using the * operator, hence the second argument in the call is *mValue . The third parameter to function FunctOne is a pointer to a long. Since pAA is itself a pointer to a long, no ampersand is needed when it is used as the third argument to the function.

Pointers and Text Strings [ edit | edit source ]

Historically, text strings in C have been implemented as arrays of characters, with the last byte in the string being a zero, or the null character '\0'. Most C implementations come with a standard library of functions for manipulating strings. Many of the more commonly used functions expect the strings to be null terminated strings of characters. To use these functions requires the inclusion of the standard C header file "string.h".

A statically declared, initialized string would look similar to the following:

The variable myFormat can be viewed as an array of 21 characters. There is an implied null character ('\0') tacked on to the end of the string after the 'd' as the 21st item in the array. You can also initialize the individual characters of the array as follows:

An initialized array of strings would typically be done as follows:

The initialization of an especially long string can be split across lines of source code as follows.

The library functions that are used with strings are discussed in a later chapter.

Pointers to Functions [ edit | edit source ]

C also allows you to create pointers to functions. Pointers to functions syntax can get rather messy. As an example of this, consider the following functions:

Declaring a typedef to a function pointer generally clarifies the code. Here's an example that uses a function pointer, and a void * pointer to implement what's known as a callback. The DoSomethingNice function invokes a caller supplied function TalkJive with caller data. Note that DoSomethingNice really doesn't know anything about what dataPointer refers to.

Some versions of C may not require an ampersand preceding the TalkJive argument in the DoSomethingNice call. Some implementations may require specifically casting the argument to the MyFunctionType type, even though the function signature exacly matches that of the typedef.

Function pointers can be useful for implementing a form of polymorphism in C. First one declares a structure having as elements function pointers for the various operations to that can be specified polymorphically. A second base object structure containing a pointer to the previous structure is also declared. A class is defined by extending the second structure with the data specific for the class, and static variable of the type of the first structure, containing the addresses of the functions that are associated with the class. This type of polymorphism is used in the standard library when file I/O functions are called.

A similar mechanism can also be used for implementing a state machine in C. A structure is defined which contains function pointers for handling events that may occur within state, and for functions to be invoked upon entry to and exit from the state. An instance of this structure corresponds to a state. Each state is initialized with pointers to functions appropriate for the state. The current state of the state machine is in effect a pointer to one of these states. Changing the value of the current state pointer effectively changes the current state. When some event occurs, the appropriate function is called through a function pointer in the current state.

Practical use of function pointers in C [ edit | edit source ]

Function pointers are mainly used to reduce the complexity of switch statement. Example with switch statement:

Without using a switch statement:

Function pointers may be used to create a struct member function:

Use to implement this pointer (following code must be placed in library).

Examples of pointer constructs [ edit | edit source ]

Below are some example constructs which may aid in creating your pointer.

sizeof [ edit | edit source ]

The sizeof operator is often used to refer to the size of a static array declared earlier in the same function.

To find the end of an array (example from wikipedia:Buffer overflow ):

To iterate over every element of an array, use

Note that the sizeof operator only works on things defined earlier in the same function. The compiler replaces it with some fixed constant number. In this case, the buffer was declared as an array of 10 char's earlier in the same function, and the compiler replaces sizeof(buffer) with the number 10 at compile time (equivalent to us hard-coding 10 into the code in place of sizeof(buffer) ). The information about the length of buffer is not actually stored anywhere in memory (unless we keep track of it separately) and cannot be programmatically obtained at run time from the array/pointer itself.

Often a function needs to know the size of an array it was given -- an array defined in some other function. For example,

Unfortunately, (in C and C++) the length of the array cannot be obtained from an array passed in at run time, because (as mentioned above) the size of an array is not stored anywhere. The compiler always replaces sizeof with a constant. This sum() routine needs to handle more than just one constant length of an array.

There are some common ways to work around this fact:

  • Write the function to require, for each array parameter, a "length" parameter (which has type "size_t"). (Typically we use sizeof at the point where this function is called).
  • Use of a convention, such as a null-terminated string to mark the end of the array.
  • Instead of passing raw arrays, pass a structure that includes the length of the array (such as ".length") as well as the array (or a pointer to the first element); similar to the string or vector classes in C++.

It's worth mentioning that sizeof operator has two variations: sizeof ( type ) (for instance: sizeof (int) or sizeof (struct some_structure) ) and sizeof expression (for instance: sizeof some_variable.some_field or sizeof 1 ).

External Links [ edit | edit source ]

  • "Common Pointer Pitfalls" by Dave Marshall

c assign int to pointer

  • Book:C Programming

Navigation menu

Everything you need to know about pointers in C

Version 1.3.1.

Copyright 2005–2023 Peter Hosey.

Creative Commons License

This document comes with a companion example program, available as one file or as multiple files (zipped) .

Style used in this document

This is regular text. This is a variable , some code , and some sample output .

This is a line of code. This is a comment. This is also a comment.
This is output you'd see on your screen.
  • Table of contents

Definition of a pointer

Starting off, interlude: declaration syntax, assignment and pointers, dereferencing, interlude: arrays, pointer arithmetic (or: why 1 == 4), interlude: structures and unions, multiple indirection, pointers and const, function pointers, strings (and why there is no such thing).

A pointer is a memory address.

(Mmm, short paragraphs.)

Say you declare a variable named foo .

This variable occupies some memory. On current mainstream Intel processors, it occupies four bytes of memory (because an int is four bytes wide).

Now let's declare another variable.

int * foo_ptr = &foo;

foo_ptr is declared as a pointer to int . We have initialized it to point to foo .

As I said, foo occupies some memory. Its location in memory is called its address. &foo is the address of foo (which is why & is called the “address-of operator”).

Think of every variable as a box. foo is a box that is sizeof(int) bytes in size. The location of this box is its address. When you access the address, you actually access the contents of the box it points to.

This is true of all variables, regardless of type. In fact, grammatically speaking, there is no such thing as a “pointer variable”: all variables are the same. There are, however, variables with different types. foo 's type is int . foo_ptr 's type is int * . (Thus, “pointer variable” really means “variable of a pointer type”.)

The point of that is that the pointer is not the variable ! The pointer to foo is the contents of foo_ptr . You could put a different pointer in the foo_ptr box, and the box would still be foo_ptr . But it would no longer point to foo .

The box named foo_ptr (an int *) is a pointer to a box named foo (an int).

The pointer has a type, too, by the way. Its type is int . Thus it is an “ int pointer” (a pointer to int ). An int ** 's type is int * (it points to a pointer to int ). The use of pointers to pointers is called multiple indirection . More on that in a bit.

The obvious way to declare two pointer variables in a single declaration is:

int* ptr_a , ptr_b ;
  • If the type of a variable containing a pointer to int is int * ,
  • and a single declaration can declare multiple variables of the same type by simply providing a comma-separated list ( ptr_a, ptr_b ),
  • then you can declare multiple int -pointer variables by simply giving the int -pointer type ( int * ) followed by a comma-separated list of names to use for the variables ( ptr_a, ptr_b ).

Given this, what is the type of ptr_b ? int * , right?

* bzzt * Wrong!

The type of ptr_b is int . It is not a pointer.

C's declaration syntax ignores the pointer asterisks when carrying a type over to multiple declarations. If you split the declaration of ptr_a and ptr_b into multiple declarations, you get this:

int *ptr_a; int ptr_b;

Think of it as assigning each variable a base type ( int ), plus a level of indirection, indicated by the number of asterisks ( ptr_b 's is zero; ptr_a 's is one).

It's possible to do the single-line declaration in a clear way. This is the immediate improvement:

int *ptr_a, ptr_b;

Notice that the asterisk has moved. It is now right next to the word ptr_a . A subtle implication of association.

It's even clearer to put the non-pointer variables first:

int ptr_b, *ptr_a;

The absolute clearest is to keep every declaration on its own line, but that can take up a lot of vertical space. Just use your own judgment.

Finally, I should point out that you can do this just fine:

int *ptr_a, *ptr_b;

There's nothing wrong with it.

Incidentally, C allows zero or more levels of parentheses around the variable name and asterisk:

int ((not_a_pointer)), (*ptr_a), (((*ptr_b)));

This is not useful for anything, except to declare function pointers (described later).

Further reading: The right-left rule for reading C declarations .

Now, how do you assign an int to this pointer? This solution might be obvious:

foo_ptr = 42;

It is also wrong.

Any direct assignment to a pointer variable will change the address in the variable, not the value at that address. In this example, the new value of foo_ptr (that is, the new “pointer” in that variable) is 42. But we don't know that this points to anything, so it probably doesn't. Trying to access this address will probably result in a segmentation violation (read: crash).

(Incidentally, compilers usually warn when you try to assign an int to a pointer variable. gcc will say “ warning: initialization makes pointer from integer without a cast ”.)

So how do you access the value at a pointer? You must dereference it.

int bar = *foo_ptr;

In this declaration, the dereference operator (prefix * , not to be confused with the multiplication operator) looks up the value that exists at an address. (This is called a “load” operation.)

It's also possible to write to a dereference expression (the C way of saying this: a dereference expression is an lvalue , meaning that it can appear on the left side of an assignment):

*foo_ptr = 42; Sets foo to 42

(This is called a “store” operation.)

Here's a declaration of a three- int array:

int array[] = { 45, 67, 89 };

Note that we use the [] notation because we are declaring an array. int *array would be illegal here; the compiler would not accept us assigning the { 45, 67, 89 } initializer to it.

This variable, array , is an extra-big box: three int s' worth of storage.

One neat feature of C is that, in most places, when you use the name array again, you will actually be using a pointer to its first element (in C terms, &array[0] ). This is called “ decaying ”: the array “decays” to a pointer. Most usages of array are equivalent to if array had been declared as a pointer.

There are, of course, cases that aren't equivalent. One is assigning to the name array by itself ( array = … )—that's illegal.

Another is passing it to the sizeof operator. The result will be the total size of the array, not the size of a pointer (for example, sizeof(array) using the array above would evaluate to ( sizeof(int) = 4) × 3 = 12 on a current Mac OS X system). This illustrates that you are really handling an array and not merely a pointer.

In most uses, however, array expressions work just the same as pointer expressions.

So, for example, let's say you want to pass an array to printf . You can't: When you pass an array as an argument to a function, you really pass a pointer to the array's first element, because the array decays to a pointer. You can only give printf the pointer, not the whole array. (This is why printf has no way to print an array: It would need you to tell it the type of what's in the array and how many elements there are, and both the format string and the list of arguments would quickly get confusing.)

Decaying is an implicit & ; array == &array == &array[0] . In English, these expressions read “ array ”, “pointer to array ”, and “pointer to the first element of array ” (the subscript operator, [] , has higher precedence than the address-of operator). But in C, all three expressions mean the same thing.

(They would not all mean the same thing if “ array ” were actually a pointer variable, since the address of a pointer variable is different from the address inside it—thus, the middle expression, &array , would not be equal to the other two expressions. The three expressions are all equal only when array really is an array.)

Say we want to print out all three elements of array .

int * array_ptr = array; printf(" first element: %i\n", *(array_ptr++)); printf("second element: %i\n", *(array_ptr++)); printf(" third element: %i\n", *array_ptr);
first element: 45 second element: 67 third element: 89

In case you're not familiar with the ++ operator: it adds 1 to a variable, the same as variable += 1 (remember that because we used the postfix expression array_ptr++ , rather than the prefix expression ++array_ptr , the expression evaluated to the value of array_ptr from before it was incremented rather than after).

But what did we do with it here?

Well, the type of a pointer matters. The type of the pointer here is int . When you add to or subtract from a pointer, the amount by which you do that is multiplied by the size of the type of the pointer. In the case of our three increments, each 1 that you added was multiplied by sizeof(int) .

By the way, though sizeof(void) is illegal, void pointers are incremented or decremented by 1 byte.

In case you're wondering about 1 == 4 : Remember that earlier, I mentioned that int s are four bytes on current Intel processors. So, on a machine with such a processor, adding 1 to or subtracting 1 from an int pointer changes it by four bytes. Hence, 1 == 4 . (Programmer humor.)

printf("%i\n", array[0]);

OK… what just happened?

This happened:

Well, you probably figured that. But what does this have to do with pointers?

This is another one of those secrets of C. The subscript operator (the [] in array[0] ) has nothing to do with arrays .

Oh, sure, that's its most common usage. But remember that, in most contexts, arrays decay to pointers. This is one of them: That's a pointer you passed to that operator, not an array.

As evidence, I submit:

int array[] = { 45, 67, 89 }; int *array_ptr = &array[1]; printf("%i\n", array_ptr[1]);

That one might bend the brain a little. Here's a diagram:

The second element of array_ptr is the third element of array.

array points to the first element of the array; array_ptr is set to &array[1] , so it points to the second element of the array. So array_ptr[1] is equivalent to array[2] ( array_ptr starts at the second element of the array, so the second element of array_ptr is the third element of the array).

Also, you might notice that because the first element is sizeof(int) bytes wide (being an int ), the second element is sizeof(int) bytes forward of the start of the array. You are correct: array[1] is equivalent to *(array + 1) . (Remember that the number added to or subtracted from a pointer is multiplied by the size of the pointer's type, so that “ 1 ” adds sizeof(int) bytes to the pointer value.)

Two of the more interesting kinds of types in C are structures and unions. You create a structure type with the struct keyword, and a union type with the union keyword.

The exact definitions of these types are beyond the scope of this article. Suffice to say that a declaration of a struct or union looks like this:

struct foo { size_t size; char name[64]; int answer_to_ultimate_question; unsigned shoe_size; };

Each of those declarations inside the block is called a member. Unions have members too, but they're used differently. Accessing a member looks like this:

struct foo my_foo; my_foo.size = sizeof(struct foo);

The expression my_foo.size accesses the member size of my_foo .

So what do you do if you have a pointer to a structure?

One way to do it (*foo_ptr).size = new_size;

But there is a better way, specifically for this purpose: the pointer-to-member operator .

Yummy foo_ptr->size = new_size;

Unfortunately, it doesn't look as good with multiple indirection.

Icky (*foo_ptr_ptr)->size = new_size; One way (**foo_ptr_ptr).size = new_size; or another

Rant: Pascal does this much better. Its dereference operator is a postfix ^ :

Yummy foo_ptr_ptr^^.size := new_size;

(But putting aside this complaint, C is a much better language.)

I want to explain multiple indirection a bit further.

Consider the following code:

int a = 3; int *b = &a; int **c = &b; int ***d = &c;

Here are how the values of these pointers equate to each other:

  • *d == c; Dereferencing an (int ***) once gets you an (int **) (3 - 1 = 2)
  • **d == *c == b; Dereferencing an (int ***) twice, or an (int **) once, gets you an (int *) (3 - 2 = 1; 2 - 1 = 1)
  • ***d == **c == *b == a == 3; Dereferencing an (int ***) thrice, or an (int **) twice, or an (int *) once, gets you an int (3 - 3 = 0; 2 - 2 = 0; 1 - 1 = 0)

Thus, the & operator can be thought of as adding asterisks (increasing pointer level, as I call it), and the * , -> , and [] operators as removing asterisks (decreasing pointer level).

The const keyword is used a bit differently when pointers are involved. These two declarations are equivalent:

const int *ptr_a; int const *ptr_a;

These two, however, are not equivalent:

int const *ptr_a; int *const ptr_b;

In the first example, the int (i.e. *ptr_a ) is const ; you cannot do *ptr_a = 42 . In the second example, the pointer itself is const ; you can change *ptr_b just fine, but you cannot change (using pointer arithmetic, e.g. ptr_b++ ) the pointer itself.

Note: The syntax for all of this seems a bit exotic. It is. It confuses a lot of people, even C wizards. Bear with me.

It's possible to take the address of a function, too. And, similarly to arrays, functions decay to pointers when their names are used. So if you wanted the address of, say, strcpy , you could say either strcpy or &strcpy . ( &strcpy[0] won't work for obvious reasons.)

When you call a function, you use an operator called the function call operator . The function call operator takes a function pointer on its left side.

In this example, we pass dst and src as the arguments on the interior, and strcpy as the function (that is, the function pointer) to be called:

enum { str_length = 18U }; Remember the NUL terminator! char src [str_length] = "This is a string.", dst [str_length]; strcpy(dst, src); The function call operator in action (notice the function pointer on the left side).

There's a special syntax for declaring variables whose type is a function pointer.

char *strcpy(char *dst, const char *src); An ordinary function declaration, for reference char *(*strcpy_ptr)(char *dst, const char *src); Pointer to strcpy-like function strcpy_ptr = strcpy; strcpy_ptr = &strcpy; This works too strcpy_ptr = &strcpy[0]; But not this

Note the parentheses around *strcpy_ptr in the above declaration. These separate the asterisk indicating return type ( char * ) from the asterisk indicating the pointer level of the variable ( *strcpy_ptr — one level, pointer to function).

Also, just like in a regular function declaration, the parameter names are optional:

char *(*strcpy_ptr_noparams)(char *, const char *) = strcpy_ptr; Parameter names removed — still the same type

The type of the pointer to strcpy is char *(*)(char *, const char *) ; you may notice that this is the declaration from above, minus the variable name. You would use this in a cast. For example:

strcpy_ptr = (char *(*)(char *dst, const char *src))my_strcpy;

As you might expect, a pointer to a pointer to a function has two asterisks inside of the parentheses:

char *(**strcpy_ptr_ptr)(char *, const char *) = &strcpy_ptr;

We can have an array of function-pointers:

char *(*strcpies[3])(char *, const char *) = { strcpy, strcpy, strcpy }; char *(*strcpies[])(char *, const char *) = { strcpy, strcpy, strcpy }; Array size is optional, same as ever strcpies[0](dst, src);

Here's a pathological declaration, taken from the C99 standard. “[This declaration] declares a function f with no parameters returning an int , a function fip with no parameter specification returning a pointer to an int , and a pointer pfi to a function with no parameter specification returning an int .” (6.7.5.3[16])

int f(void), *fip(), (*pfi)();

In other words, the above is equivalent to the following three declarations:

int f(void); int *fip(); Function returning int pointer int (*pfi)(); Pointer to function returning int

But if you thought that was mind-bending, brace yourself…

A function pointer can even be the return value of a function. This part is really mind-bending, so stretch your brain a bit so as not to risk injury.

In order to explain this, I'm going to summarize all the declaration syntax you've learned so far. First, declaring a pointer variable:

This declaration tells us the pointer type ( char ), pointer level ( * ), and variable name ( ptr ). And the latter two can go into parentheses:

char (*ptr);

What happens if we replace the variable name in the first declaration with a name followed by a set of parameters?

char *strcpy(char *dst, const char *src);

Huh. A function declaration.

But we also removed the * indicating pointer level — remember that the * in this function declaration is part of the return type of the function. So if we add the pointer-level asterisk back (using the parentheses):

char *(*strcpy_ptr)(char *dst, const char *src);

A function pointer variable!

But wait a minute. If this is a variable, and the first declaration was also a variable, can we not replace the variable name in THIS declaration with a name and a set of parameters?

YES WE CAN! And the result is the declaration of a function that returns a function pointer:

char *(*get_strcpy_ptr(void))(char *dst, const char *src);

Remember that the type of a pointer to a function taking no arguments and returning int is int (*)(void) . So the type returned by this function is char *(*)(char *, const char *) (with, again, the inner * indicating a pointer, and the outer * being part of the return type of the pointed-to function). You may remember that that is also the type of strcpy_ptr .

So this function, which is called with no parameters, returns a pointer to a strcpy -like function:

strcpy_ptr = get_strcpy_ptr();

Because function pointer syntax is so mind-bending, most developers use typedef s to abstract them:

typedef char *(*strcpy_funcptr)(char *, const char *); strcpy_funcptr strcpy_ptr = strcpy; strcpy_funcptr get_strcpy_ptr(void);

There is no string type in C.

Now you have two questions:

  • Why do I keep seeing references to “C strings” everywhere if there is no string type?
  • What does this have to do with pointers?

The truth is, the concept of a “C string” is imaginary (except for string literals). There is no string type. C strings are really just arrays of characters:

char str[] = "I am the Walrus";

This array is 16 bytes in length: 15 characters for "I am the Walrus", plus a NUL (byte value 0) terminator. In other words, str[15] (the last element) is 0. This is how the end of the “string” is signaled.

This idiom is the extent to which C has a string type. But that's all it is: an idiom. Except that it is supported by:

  • the aforementioned string literal syntax
  • the string library

The functions in string.h are for string manipulation. But how can that be, if there is no string type?

Why, they work on pointers.

Here's one possible implementation of the simple function strlen , which returns the length of a string (not including the NUL terminator):

size_t strlen(const char *str) { Note the pointer syntax here size_t len = 0U; while(*(str++)) ++len; return len; }

Note the use of pointer arithmetic and dereferencing. That's because, despite the function's name, there is no “string” here; there is merely a pointer to at least one character, the last one being 0.

Here's another possible implementation:

size_t strlen(const char *str) { size_t i; for(i = 0U; str[i]; ++i); When the loop exits, i is the length of the string return i; }

That one uses indexing. Which, as we found out earlier, uses a pointer (not an array, and definitely not a string).

Version history

  • Replaced hotlinked Creative Commons bug with my own high-resolution redraw of it.
  • Upgraded various links to HTTPS, and replaced dead links with corrected ones or Wayback Machine links.
  • Switched character set to UTF-8.
  • Fixed explanation of the relationship between Pointers and const .
  • Added -> as one of the dereference operators in Multiple indirection .
  • Changed improper use of ‘’’ as apostrophe to use proper apostrophes instead. Most fonts still render the apostrophe (‘'’) as a straight single quote, but that's not my problem.
  • Corrected discussion of decaying, especially of arrays. Arrays are not pointers.
  • Added two links to the right-left rule for reading C declarations .
  • Corrected the name of the subscript operator (which I previously referred to as the index operator).
  • Replaced references to the PowerPC with references to Intel processors. (Fortunately, no factual changes were necessary.)
  • Fixed a couple of compilation errors and a few warnings in the sample code (in addition to the aforementioned array-decaying discussion).
  • Fixed link to the Pointer arithmetic section from the 1.1 section below.
  • Changed the hyphen to an en dash in the year range in the copyright notice (reference: Chicago Manual of Style ).
  • Changed byline from “Mac-arena the Bored Zo” to my real name.
  • Added Function pointers section.
  • Added Pointers and const section.
  • Added note about parentheses in declarators in Declaration syntax .
  • Added that array == &array == &array[0] (i.e. decay is an implicit & ) in Arrays .
  • Smart quotes.
  • Reworded parenthetical about ++x vs x++ , at Colin Barrett's suggestion.
  • Assignment section (describing the action of foo_ptr = 42 )
  • Declaration syntax section
  • Multiple indirection section
  • C strings section
  • Changed sentences to begin with a capital letter, on feedback that it should be clearer to read that way.
  • Clarified 1 == 4 expression in title, and use of ++ , in “ Pointer arithmetic ”.
  • Shinier CSS, especially for comments.
  • Added winged-comments ( example ) style.
  • Added diagram in Starting off .
  • Explained array declaration syntax (as opposed to pointer declaration syntax) in Arrays .

This document is also available in zip format. The previous versions ( 1.2.1 , 1.2 , 1.1 , and 1.0 ) are also available.

Note: You are looking at a static copy of the former PineWiki site, used for class notes by James Aspnes from 2003 to 2012. Many mathematical formulas are broken, and there are likely to be other bugs as well. These will most likely not be fixed. You may be able to find more up-to-date versions of some of these notes at http://www.cs.yale.edu/homes/aspnes/#classes .

  • Memory and addresses
  • Declaring a pointer variable
  • Assigning to pointer variables
  • Using a pointer
  • Printing pointers
  • The null pointer
  • Pointers and functions
  • Arrays and functions
  • Multidimensional arrays
  • Variable-length arrays
  • Void pointers
  • Run-time storage allocation
  • The restrict keyword

1. Memory and addresses

2. pointer variables, 2.1. declaring a pointer variable, 2.2. assigning to pointer variables, 2.3. using a pointer, 2.4. printing pointers, 3. the null pointer, 4. pointers and functions, 5. pointer arithmetic and arrays, 5.1. arrays and functions, 5.2. multidimensional arrays, 5.3. variable-length arrays, 6. void pointers, 7. run-time storage allocation, 8. the restrict keyword.

cppreference.com

Pointer declaration.

Pointer is a type of an object that refers to a function or an object of another type, possibly adding qualifiers. Pointer may also refer to nothing, which is indicated by the special null pointer value.

[ edit ] Syntax

In the declaration grammar of a pointer declaration, the type-specifier sequence designates the pointed-to type (which may be function or object type and may be incomplete), and the declarator has the form:

where declarator may be the identifier that names the pointer being declared, including another pointer declarator (which would indicate a pointer to a pointer):

The qualifiers that appear between * and the identifier (or other nested declarator) qualify the type of the pointer that is being declared:

The attr-spec-seq (C23) is an optional list of attributes , applied to the declared pointer.

[ edit ] Explanation

Pointers are used for indirection, which is a ubiquitous programming technique; they can be used to implement pass-by-reference semantics, to access objects with dynamic storage duration , to implement "optional" types (using the null pointer value), aggregation relationship between structs, callbacks (using pointers to functions), generic interfaces (using pointers to void), and much more.

[ edit ] Pointers to objects

A pointer to object can be initialized with the result of the address-of operator applied to an expression of object type (which may be incomplete):

Pointers may appear as operands to the indirection operator (unary * ), which returns the lvalue identifying the pointed-to object:

Pointers to objects of struct and union type may also appear as the left-hand operands of the member access through pointer operator -> .

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:

Certain addition, subtraction , compound assignment , increment, and decrement operators are defined for pointers to elements of arrays.

Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indexes of those elements, and pointers to struct members compare in order of declaration of those members.

Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous ("flat") virtual address space.

[ edit ] Pointers to functions

A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional:

Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc.

A pointer to function can be used on the left-hand side of the function call operator ; this invokes the pointed-to function:

Dereferencing a function pointer yields the function designator for the pointed-to function:

Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).

Because compatibility of function types ignores top-level qualifiers of the function parameters, pointers to functions whose parameters only differ in their top-level qualifiers are interchangeable:

[ edit ] Pointers to void

Pointer to object of any type can be implicitly converted to pointer to void (optionally const or volatile -qualified), and vice versa:

Pointers to void are used to pass objects of unknown type, which is common in generic interfaces: malloc returns void * , qsort expects a user-provided callback that accepts two const void * arguments. pthread_create expects a user-provided callback that accepts and returns void * . In all cases, it is the caller's responsibility to convert the pointer to the correct type before use.

[ edit ] Null pointers

Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (dereferencing a null pointer is undefined behavior), and compares equal to all pointers of the same type whose value is also null .

To initialize a pointer to null or to assign the null value to an existing pointer, a null pointer constant ( NULL , or any other integer constant with the value zero) may be used. static initialization also initializes pointers to their null values.

Null pointers can indicate the absence of an object or can be used to indicate other types of error conditions. In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, free does nothing when a null pointer is passed).

[ edit ] Notes

Although any pointer to object can be cast to pointer to object of a different type, dereferencing a pointer to the type different from the declared type of the object is almost always undefined behavior. See strict aliasing for details.

lvalue expressions of array type, when used in most contexts, undergo an implicit conversion to the pointer to the first element of the array. See array for details.

Pointers to char are often used to represent strings . To represent a valid byte string, a pointer must be pointing at a char that is an element of an array of char, and there must be a char with the value zero at some index greater or equal to the index of the element referenced by the pointer.

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.6.1 Pointer declarators (p: 93-94)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.6.1 Pointer declarators (p: 130)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.5.1 Pointer declarators (p: 115-116)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.5.4.1 Pointer declarators

[ edit ] See also

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 15 June 2021, at 08:34.
  • This page has been accessed 68,822 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Pointer Basics

Section 1 -- pointer rules, 1) pointers and pointees, 2) dereferencing, 3) pointer assignment, section 2 -- binky's code example, java version, c++ version, pascal version, section 3 -- study questions.

Pointers in C Explained – They're Not as Difficult as You Think

Pointers are arguably the most difficult feature of C to understand. But, they are one of the features which make C an excellent language.

In this article, we will go from the very basics of pointers to their usage with arrays, functions, and structure.

So relax, grab a coffee, and get ready to learn all about pointers.

A. Fundamentals

  • What exactly are pointers?
  • Definition and Notation
  • Some Special Pointers
  • Pointer Arithmetic

B. Arrays and Strings

  • Why pointers and arrays?
  • Array of Pointers
  • Pointer to Array

C. Functions

  • Call by Value v/s Call by Reference
  • Pointers as Function Arguments
  • Pointers as Function Return
  • Pointer to Function
  • Array Of Pointers to Functions
  • Pointer to Function as an Argument

D. Structure

  • Pointer to Structure
  • Array of Structure
  • Pointer to Structure as an Argument

E. Pointer to Pointer

F. conclusion, a. definition, notation, types and arithmetic, 1. what exactly are pointers.

Before we get to the definition of pointers, let us understand what happens when we write the following code:

What exactly are pointers?

A block of memory is reserved by the compiler to hold an int value. The name of this block is digit and the value stored in this block is 42 .

Now, to remember the block, it is assigned with an address or a location number (say, 24650).

The value of the location number is not important for us, as it is a random value. But, we can access this address using the & (ampersand) or address of operator.

We can get the value of the variable digit from its address using another operator * (asterisk), called the indirection or dereferencing or value at address operator.

2. Definition and Notation

The address of a variable can be stored in another variable known as a pointer variable. The syntax for storing a variable's address to a pointer is:

For our digit variable, this can be written like this:

or like this:

This can be read as - A pointer to int (integer) addressOfDigit stores the address of(&) digit variable.

Few points to understand:

dataType – We need to tell the computer what the data type of the variable is whose address we are going to store. Here, int was the data type of digit .

It does not mean that addressOfDigit will store a value of type int . An integer pointer (like addressOfDigit ) can only store the address of variables of integer type.

* – A pointer variable is a special variable in the sense that it is used to store an address of another variable. To differentiate it from other variables that do not store an address, we use * as a symbol in the declaration.

Here, we can assign the address of variable1 and variable2 to the integer pointer addressOfVariables but not to variable3 since it is of type char . We will need a character pointer variable to store its address.

We can use our addressOfDigit pointer variable to print the address and the value of digit as below:

Here, *addressOfDigit can  be read as the value at the address stored in addressOfDigit .

Notice we used %d as the format identifier for addressOfDigit . Well, this is not completely correct. The correct identifier would be %p .

Using %p , the address is displayed as a hexadecimal value. But the memory address can be displayed in integers as well as octal values. Still, since it is not an entirely correct way, a warning is shown.

The output according to the compiler I'm using is the following:

This is the warning shown when you use  %d - " warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' ".

3. Some Special Pointers

The wild pointer.

When we defined our character pointer alphabetAddress , we did not initialize it.

Such pointers are known as wild pointers . They store a garbage value (that is, memory address) of a byte that we don't know is reserved or not (remember int digit = 42; , we reserved a memory address when we declared it).

Suppose we dereference a wild pointer and assign a value to the memory address it is pointing at. This will lead to unexpected behaviour since we will write data at a  memory block that may be free or reserved.

Null Pointer

To make sure that we do not have a wild pointer, we can initialize a pointer with a NULL value, making it a null pointer .

A null pointer points at nothing, or at a memory address that users can not access.

Void Pointer

A void pointer can be used to point at a variable of any data type. It can be reused to point at any data type we want to. It is declared like this:

Since they are very general in nature, they are also known as generic pointers .

With their flexibility, void pointers also bring some constraints. Void pointers cannot be dereferenced as any other pointer. Appropriate typecasting is necessary.

Similarly, void pointers need to be typecasted for performing arithmetic operations.

Void pointers are of great use in C. Library functions malloc() and calloc() which dynamically allocate memory return void pointers. qsort() , an inbuilt sorting function in C, has a function as its argument which itself takes void pointers as its argument.

Dangling Pointer

A dangling pointer points to a memory address which used to hold a variable. Since the address it points at is no longer reserved, using it will lead to unexpected results.

Though the memory has been deallocated by free(ptr) , the pointer to integer ptr still points to that unreserved memory address.

4. Pointer Arithmetic

We know by now that pointers are not like any other variable. They do not store any value but the address of memory blocks.

So it should be quite clear that not all arithmetic operations would be valid with them. Would multiplying or dividing two pointers ( having addresses ) make sense?

Pointers have few but immensely useful valid operations:

  • You can assign the value of one pointer to another only if they are of the same type (unless they're typecasted or one of them is void * ).

2.   You can only add or subtract integers to pointers.

When you add (or subtract) an integer (say n) to a pointer, you are not actually adding (or subtracting) n bytes to the pointer value. You are actually adding (or subtracting) n- times the size of the data type of the variable being pointed bytes.

The value stored in newAddress will not be 103, rather 112 .

3.   Subtraction and comparison of pointers is valid only if both are members of the same array. The subtraction of pointers gives the number of elements separating them.

4.  You can assign or compare a pointer with NULL .

The only exception to the above rules is that the address of the first memory block after the last element of an array follows pointer arithmetic.

Pointer and arrays exist together. These valid manipulations of pointers are immensely useful with arrays, which will be discussed in the next section.

1. Why pointers and arrays?

In C, pointers and arrays have quite a strong relationship.

The reason they should be discussed together is because what you can achieve with array notation ( arrayName[index] ) can also be achieved with pointers, but generally faster.

2. 1-D Arrays

Let us look at what happens when we write int myArray[5]; .

Five consecutive blocks of memory starting from myArray[0] to myArray[4] are created with garbage values in them. Each of the blocks is of size 4 bytes.

Thus, if the address of myArray[0] is 100 (say), the address of the rest of the blocks would be 104 , 108 , 112 , and 116 .

Have a look at the following code:

So, &prime , prime , and &prime[0] all give the same address, right? Well, wait and read because you are in for a surprise (and maybe some confusion).

Let's try to increment each of &prime , prime , and &prime[0] by 1.

Wait! How come &prime + 1 results in something different than the other two? And why are prime + 1 and &prime[0] + 1 still equal? Let's answer these questions.

prime and &prime[0] both point to the 0th element of the array prime . Thus, the name of an array is itself a pointer to the 0th element of the array .

Here, both point to the first element of size 4 bytes. When you add 1 to them, they now point to the 1st element in the array. Therefore this results in an increase in the address by 4.

&prime , on the other hand, is a pointer to an int array of size 5 . It stores the base address of the array prime[5] , which is equal to the address of the first element. However, an increase by 1 to it results in an address with an increase of 5 x 4 = 20 bytes.

In short, arrayName and &arrayName[0] point to the 0th element whereas &arrayName points to the whole array.

We can access the array elements using subscripted variables like this:

We can do the same using pointers which are always faster than using subscripts.

Both methods give the output:

Thus, &arrayName[i] and arrayName[i] are the same as arrayName + i and   *(arrayName + i) , respectively.

3. 2-D Arrays

Two-dimensional arrays are an array of arrays.

Here, marks can be thought of as an array of 5 elements, each of which is a one-dimensional array containing 3 integers. Let us work through a series of programs to understand different subscripted expressions.

Like 1-D arrays, &marks points to the whole 2-D array, marks[5][3] . Thus, incrementing to it by 1 ( = 5 arrays X 3 integers each X 4 bytes = 60) results in an increment by 60 bytes.

If marks was a 1-D array, marks and &marks[0] would have pointed to the 0th element. For a 2-D array, elements are now 1-D arrays . Hence, marks and &marks[0] point to the 0th array (element), and the addition of 1 point to the 1st array.

And now comes the difference. For a 1-D array, marks[0] would give the value of the 0th element. An increment by 1 would increase the value by 1.

But, in a 2-D array, marks[0] points to the 0th element of the 0th array. Similarly, marks[1] points to the 0th element of the 1st array. An increment by 1 would point to the 1st element in the 1st array.

This is the new part. marks[i][j] gives the value of the jth element of the ith array. An increment to it changes the value stored at marks[i][j] . Now, let us try to write marks[i][j] in terms of pointers.

We know marks[i] + j would point to the ith element of the jth array from our previous discussion. Dereferencing it would mean the value at that address. Thus, marks[i][j] is the same as   *(marks[i] + j) .

From our discussion on 1-D arrays, marks[i] is the same as *(marks + i) . Thus, marks[i][j] can be written as *(*(marks + i) + j) in terms of pointers.

Here is a summary of notations comparing 1-D and 2-D arrays.

A string is a one-dimensional array of characters terminated by a null(\0) . When we write char name[] = "Srijan"; , each character occupies one byte of memory with the last one always being \0 .

Similar to the arrays we have seen, name and &name[0] points to the 0th character in the string, while &name points to the whole string. Also, name[i] can be written as *(name + i) .

A two-dimensional array of characters or an array of strings can also be accessed and manipulated as discussed before.

5. Array of Pointers

Like an array of int s and an array of char s, there is an array of pointers as well. Such an array would simply be a collection of addresses. Those addresses could point to individual variables or another array as well.

The syntax for declaring a pointer array is the following:

Following the operators precedence , the first example can be read as -   example1 is an array( [] ) of 5 pointers to int . Similarly, example2 is an array of 8 pointers to char .

We can store the two-dimensional array to string top using a pointer array and save memory as well.

top will contain the base addresses of all the respective names. The base address of "Liverpool" will be stored in top[0] , "Man City" in top[1] , and so on.

In the earlier declaration, we required 90 bytes to store the names. Here, we only require ( 58 (sum of bytes of names) + 12 ( bytes required to store the address in the array) ) 70 bytes.

The manipulation of strings or integers becomes a lot easier when using an array of pointers.

If we try to put "Leicester" ahead of "Chelsea" , we just need to switch the values of top[3] and top[4] like below:

Without pointers, we would have to exchange every character of the strings, which would have taken more time. That's why strings are generally declared using pointers.

6. Pointer to Array

Like "pointer to int " or "pointer to char ", we have pointer to array as well. This pointer points to whole array rather than its elements.

Remember we discussed how &arrayName points to the whole array? Well, it is a pointer to array.

A pointer to array can be declared like this:

Notice the parentheses. Without them, these would be an array of pointers. The first example can be read as - ptr1 is a pointer to an array of 5 int (integers) .

When we dereference a pointer, it gives the value at that address. Similarly, by dereferencing a pointer to array, we get the array and the name of the array points to the base address. We can confirm that *pointerToGoals gives the array goals if we find its size.

If we dereference it again, we will get the value stored in that address. We can print all the elements using pointerToGoals .

Pointers and pointer to arrays are quite useful when paired up with functions. Coming up in the next section!

1. Call by Value vs Call by Reference

Have a look at the program below:

The function multiply() takes two int arguments and returns their product as int .

In the function call multiply(x,y) , we passed the value of x and y ( of main() ), which are actual arguments , to multiply() .

The values of the actual arguments are passed or copied to the formal arguments x and y ( of multiply() ). The x and y of multiply() are different from those of main() . This can be verified by printing their addresses.

Since we created stored values in a new location, it costs us memory. Wouldn't it be better if we could perform the same task without wasting space?

Call by reference helps us achieve this. We pass the address or reference of the variables to the function which does not create a copy. Using the dereferencing operator * , we can access the value stored at those addresses.

We can rewrite the above program using call by reference as well.

2. Pointers as Function Arguments

In this section, we will look at various programs where we give int , char , arrays and strings as arguments using pointers.

We created four functions, add() , subtract() , multiply() and divide() to perform arithmetic operations on the two numbers a and b .

The address of a and b was passed to the functions. Inside the function using * we accessed the values and printed the result.

Similarly, we can give arrays as arguments using a pointer to its first element.

Since the name of an array itself is a pointer to the first element, we send that as an argument to the function greatestOfAll() . In the function, we traverse through the array using loop and pointer.

Here, we pass in the string name to wish() using a pointer and print the message.

3. Pointers as Function Return

The function multiply() takes two pointers to int . It returns a pointer to int as well which stores the address where the product is stored.

It is very easy to think that the output would be 15. But it is not!

When multiply() is called, the execution of main() pauses and memory is now allocated for the execution of multiply() . After its execution is completed, the memory allocated to multiply() is deallocated.

Therefore, though c ( local to main() ) stores the address of the product, the data there is not guaranteed since that memory has been deallocated.

So does that mean pointers cannot be returned by a function? No!

We can do two things. Either store the address in the heap or global section or declare the variable to be static so that their values persist.

Static variables can simply be created by using the keyword static before data type while declaring the variable.

To store addresses in heap, we can use library functions malloc() and calloc() which allocate memory dynamically.

The following programs will explain both the methods. Both methods return the output as 15.

4. Pointer to Function

Like pointer to different data types, we also have a pointer to function as well.

A pointer to function or function pointer stores the address of the function. Though it doesn't point to any data. It points to the first instruction in the function.

The syntax for declaring a pointer to function is:

The below example will make it clearer.

The declaration for the pointer p to function multiply() can be read as ( following operator precedence ) - p is a pointer to function with two int eger pointers ( or two pointers to int ) as parameters and returning a pointer to int .

Since the name of the function is also a pointer to the function, the use of & is not necessary. Also removing * from the function call doesn't affect the program.

5. Array of Pointers to Functions

We have already seen how to create an array of pointers to int , char , and so on. Similarly, we can create an array of pointers to function.

In this array, every element will store an address of a function, where all the functions are of the same type. That is, they have the same type and number of parameters and return types.

We will modify a program discussed earlier in this section. We will store the addresses of add() , subtract() , multiply() and divide() in an array make a function call through subscript.

The declaration here can be read as - p is an array of pointer to functions with two float pointers as parameters and returning void .

6. Pointer to Function as an Argument

Like any other pointer, function pointers can also be passed to another function, therefore known as a callback function or called function . The function to which it is passed is known as a calling function .

A better way to understand would be to look at qsort() , which is an inbuilt function in C. It is used to sort an array of integers, strings, structures, and so on. The declaration for qsort() is:

qsort() takes four arguments:

  • a void pointer to the start of an array
  • number of elements
  • size of each element
  • a function pointer that takes in two void pointers as arguments and returns an int

The function pointer points to a comparison function that returns an integer that is greater than, equal to, or less than zero if the first argument is respectively greater than, equal to, or less than the second argument.

The following program showcases its usage:

Since a function name is itself a pointer, we can write compareIntegers as the fourth argument.

1. Pointer to Structure

Like integer pointers, array pointers, and function pointers, we have pointer to structures or structure pointers as well.

Here, we have declared a pointer ptrStudent of type struct records . We have assigned the address of student to ptrStudent .

ptrStudent stores the base address of student , which is the base address of the first member of the structure. Incrementing by 1 would increase the address by sizeof(student) bytes.

We can access the members of student using ptrStudent in two ways. Using our old friend * or using -> ( infix or arrow operator ).

With * , we will continue to use the . ( dot operator) whereas with -> we won't need the dot operator.

Similarly, we can access and modify other members as well. Note that the brackets are necessary while using * since the dot operator( . ) has higher precedence over * .

2. Array Of Structure

We can create an array of type struct records and use a pointer to access the elements and their members.

Note that ptrStudent1 is a pointer to student[0] whereas ptrStudent2 is a pointer to the whole array of  10 struct records . Adding 1 to ptrStudent1 would point to student[1] .

We can use ptrStudent1 with a loop to traverse through the elements and their members.

3. Pointer to Structure as an Argument

We can also pass the address of a structure variable to a function.

Note that the structure struct records is declared outside main() . This is to ensure that it is available globally and printRecords() can use it.

If the structure is defined inside main() , its scope will be limited to main() . Also structure must be declared before the function declaration as well.

Like structures, we can have pointers to unions and can access members using the arrow operator ( -> ).

So far we have looked at pointer to various primitive data types, arrays, strings, functions, structures, and unions.

The automatic question that comes to the mind is – what about pointer to pointer?

Well, good news for you! They too exist.

To store the address of int variable var , we have the pointer to int ptr_var . We would need another pointer to store the address of ptr_var .

Since ptr_var is of type int * , to store its address we would have to create a pointer to int * . The code below shows how this can be done.

We can use ptr_ptrvar to access the address of ptr_var and use double dereferencing to access var.

It is not required to use brackets when dereferencing ptr_ptrvar . But it is a good practice to use them. We can create another pointer ptr_ptrptrvar , which will store the address of ptr_ptrvar .

Since ptr_ptrvar is of type int** , the declaration for ptr_ptrptrvar will be

We can again access ptr_ptrvar , ptr_var and var using ptr_ptrptrvar .

If we change the value at any of the pointer(s) using ptr_ptrptrvar or ptr_ptrvar , the pointer(s) will stop pointing to the variable.

Phew! Yeah, we're finished. We started from pointers and ended with pointers (in a way). Don't they say that the curve of learning is a circle!

Try to recap all the sub-topics that you read. If you can recollect them, well done! Read the ones you can't remember again.

This article is done, but you shouldn't be done with pointers. Play with them. Next, you can look into Dynamic Memory Allocation to get to know pointers better .

Stay home, stay safe.

Sachin. Cricket. Dhoni. De Villiers. Buttler. In that order.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

c assign int to pointer

  • Website Rank
  • ASP.net Examples
  • EMI Calculator

c assign int to pointer

C Data Types

C arithmetic operators, c switch case, c function arguments, c functions returning pointers, c dynamic memory allocations, c array elements memory locations, c passing array to a function, c access array elements, c print string elements using pointer, c string functions, c string length, c string index, c escape sequences, c structures, nested structures, passing structure variable, c structure pointers, c array of structures, c file pointers, c text file write, c text file read, c binary file write, c binary file read, scanf character issue, pointers to function, command line arguments, multiple return values, implicit function declaration warning, c define directive, c include directive, c ifdef directive, undefined reference to pow, c gets function, c storage classes, switch case, conditional operator, reverse order for loop, for with multiple initializations, c programming pointers for int, float and char.

A pointer is a variable that holds the memory address of another variable (direct address of the memory location).

Every byte in the computer's memory has an address, so pointer holds the address through which variable can be directly accessed.

Addresses are just numbers as our house numbers, and address starts at NULL and goes up from 1,2, 3 etc..

Need to declare a pointer before using it to store any variable address.

Let us consider below decalration,

a is the integer variable and reserves the space in memory to hold integer value 25.

b is the integer pointer and can contain the address of integer variable a.

Value at address contained in b is an integer.

Similarly need to declare b as float pointer if needs to contain the address of float variable.

int, float, char Pointers in C Program

This c program explains how to use the pointers with int, float and character data types.

C Pointers Type Casting Example:

2 bytes used to store integer value and for character 1 bytes. during char * type casting, considers only first 1 byte of data and not another byte.

What will happen if we use incorrect pointer type?

Incorrect values (garbage values) returned for incorrect pointers.

Warning message is thrown as 'incompatible pointer type' in compilation.

C program to cmpute matrix addition using two dimensional array

C program to cmpute matrix subtraction using two dimensional array, c program to cmpute matrix multiplication using two dimensional array, c program to compute different order of matrix multiplication, c program to generate identity matrix for required rows and columns, c program to validate whether matrix is identity matrix or not, c program to validate whether matrix is sparse matrix or not, c program to validate whether matrix is dense matrix or not, c program to generate string as matrix diagonal characters using two dimesional array, c program to find number of weeks, months and years from days, c program to implement linked list and operations, c program to implement sorted linked list and operations, c program to reverse the linked list, c program to stack and operations using linked list, c program to queue and operations using linked list, c program to calculate multiplication of two numbers using pointers, c program to calculate median, c program to calculate standard deviation, c program for fahrenheit to celsius conversion, c program to calculate average, c program for quadratic equations, c program to check character type, c program to find largest of three values, c program to find max value in array, c program to find min value in array, c program to print multiplication table, c program for frequency counting, c program to read a line of text, c program to find ascii value for any character, c program to find a character is number, alphabet, operator, or special character, c program to find reverse case for any alphhabet using ctype functions, c program to find number of vowels in input string, c program pointers example code, c program to find leap year or not, c program to swap two integers using call by reference, c program to swap two integers without using third variable, c program to list prime numbers upto limit, c program to list composite numbers upto limit, c program to calculate compound interest, c program to calculate depreciation amount after of before few years, c program to calculate profit percentage, c program to calculate loss percentage, c program to find string is polindrome or not, c program to find factorial of a number, c program to check number is a polindrome or not, c program to generate random integers, c program to generate random float numbers, c program to find square root of a number, c program to find area of a rectangle, c program to find perimeter of a rectangle, c program to find area of a square, c program to find area of a triangle, c program to find area of a parallelogram, c program to find area of a rhombus, c program to find area of a trapezium, c program to find area of a circle and semi-circle, c program to find circumference of a circle and semi-circle, c program to find length of an arc, c program to find area of a sector, c program to find string length for list of strings, c program to find the character at index in a string, c program to compare characters, c program to find eligible to vote or not, c program to get system current date and time on linux, c program to get positive number, c program to implement calculator, c program to implement banking system, c program to find sum of number, c program for array traversal using pointers, c program for array traversal in reverse order using pointers, c program to find particular element occurrences count in array, c program to find even elements occurrences count in array, c program to find odd elements occurrences count in array, c program to find week day in word from week day in number using two dimentsional array, c program to find month in word from month in number using pointers, c program to compute pmt for a loan, c program to compute emi and round up using floor, c program to compute emi and round up using ceil, c program to compute the emi table with interest, principal and balance, c program to get multiple line of string, c program to find nth element in array using pointers, c program to compute the volume of a cube, c program to compute the volume of a box, c program to compute the volume of a sphere, c program to compute the volume of a triangular prism, c program to compute the volume of a cylinder, c program to compute perimeter of square, c program to compute the perimeter of triangle, c program to compute the discount rate, c program to compute the sales tax, c program to add, delete, search a record or show all using binary file, c program to add, delete, search a record or show all using text file.

copyright symbol

C Programming Tutorial

  • Void Pointers in C

Last updated on July 27, 2020

We have learned in chapter Pointer Basics in C that if a pointer is of type pointer to int or (int *) then it can hold the address of the variable of type int only. It would be incorrect, if we assign an address of a float variable to a pointer of type pointer to int . But void pointer is an exception to this rule. A void pointer can point to a variable of any data type. Here is the syntax of void pointer.

Syntax: void *vp;

Let's take an example:

Here vp is a void pointer, so you can assign the address of any type of variable to it.

A void pointer can point to a variable of any data type and void pointer can be assigned to a pointer of any type.

Dereferencing a void Pointer #

We can't just dereference a void pointer using indirection ( * ) operator. For example:

It simply doesn't work that way!. Before you dereference a void pointer it must be typecasted to appropriate pointer type. Let me show you what I mean.

For example: In the above snippet void pointer vp is pointing to the address of integer variable a. So in this case vp is acting as a pointer to int or (int *) . Hence the proper typecast in this case is (int*) .

Now the type of vptr temporarily changes from void pointer to pointer to int or (int*) , and we already know how to dereference a pointer to int , just precede it with indirection operator ( * )

Note: typecasting changes type of vp temporarily until the evaluation of the expression, everywhere else in the program vp is still a void pointer.

The following program demonstrates how to dereference a void pointer.

Expected Output:

Pointer Arithmetic in Void Pointers #

Another important point I want to mention is about pointer arithmetic with void pointer. Before you apply pointer arithmetic in void pointers make sure to provide a proper typecast first otherwise you may get unexcepted results.

Consider the following example:

Here we have assigned the name of the array one_d to the void pointer vp . Since the base type of one_d is a pointer to int or (int*) , the void pointer vp is acting like a pointer to int or (int*) . So the proper typecast is (int*) .

The following program demonstrates pointer arithmetic in void pointers.

The void pointers are used extensively in dynamic memory allocation which we will discuss next.

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

IMAGES

  1. C Pointer to Pointer (Theory & Example)

    c assign int to pointer

  2. Pointers in C with Examples

    c assign int to pointer

  3. C Pointers

    c assign int to pointer

  4. How to Create Pointers in C: 12 Steps (with Pictures)

    c assign int to pointer

  5. How do pointer-to-pointers work in C? (and when might you use them

    c assign int to pointer

  6. Pointer to Pointer in C Programming Language Video Tutorials for Beginners

    c assign int to pointer

VIDEO

  1. 14. this pointer in c++

  2. C++

  3. C++ 106 For loops and Dynamic Arrays

  4. C++ Pointer Part 2

  5. Array : Can't assign string to pointer inside struct

  6. C++ pointers part2 sec10_2

COMMENTS

  1. Directly assigning values to C Pointers

    The whole problem is that you don't assign a value to the pointer. - Keith Thompson

  2. C Pointers (With Examples)

    Here is how we can declare pointers. int* p; Here, we have declared a pointer p of int type. You can also declare pointers in these ways. int *p1; int * p2; Let's take another example of declaring pointers. int* p1, p2; Here, we have declared a pointer p1 and a normal variable p2. Assigning addresses to Pointers Let's take an example.

  3. Pointers in C

    Articles Pointers in C - Declare, initialize and use Categories C programming 7 mins readMay 6, 2018October 20, 2017 Pointers are the heart of C programming. It is the most distinct feature of C, which provides power and flexibility to C. Pointers separates C from other programming languages.

  4. C Pointers

    The use of pointers in C can be divided into three steps: Pointer Declaration Pointer Initialization Pointer Dereferencing 1. Pointer Declaration In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. Example int *ptr;

  5. Converting Int to Pointer in C

    C programming allows developers to perform intricate operations, one of which involves casting an integer to a pointer. This process can be complex, and it's crucial for a deep understanding of the language. In this blog, we will explore different methods of converting an integer to a pointer in C Method 1: Explicit Casting

  6. How C-Pointers Works: A Step-by-Step Beginner's Tutorial

    For example: int *ptr; declares 'ptr' as a pointer to an integer. Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to. Pointer Arithmetic:

  7. Pointers in C Programming with examples

    By using * operator we can access the value of a variable through a pointer. For example: double a = 10; double *p; p = &a; *p would give us the value of the variable a. The following statement would display 10 as output. printf("%d", *p); Similarly if we assign a value to *pointer like this: *p = 200;

  8. C Programming/Pointers and arrays

    How to declare them (with the address operator ' & ': int *pointer = &variable;) How to assign to them ( pointer = NULL;) How to reference the value to which the pointer points (known as dereferencing, by using the dereferencing operator ' * ': value = *pointer;)

  9. Pointer Basics

    ptr = 0; The null pointer is the integer literal that may be assigned to a pointer. You may NOT assign arbitrary numbers to pointers: int * p = 0; // okay. assignment of null pointer to p int * q; q = 0; // okay. null pointer again. int * z; z = 900; // BAD! cannot assign other literals to pointers! double * dp; dp = 1000; // BAD!

  10. Everything you need to know about pointers in C

    Assignment and pointers. Now, how do you assign an int to this pointer? This solution might be obvious: foo_ptr = 42; It is also wrong. Any direct assignment to a pointer variable will change the address in the variable, not the value at that address. In this example, the new value of foo_ptr (that is, the new "pointer" in that variable) is 42. But we don't know that this points to ...

  11. C/Pointers

    Declaring a pointer variable. The convention is C is that the declaration of a complex type looks like its use. To declare a pointer-valued variable, write a declaration for the thing that it points to, but include a * before the variable name: int *; 2 double *; 3 char *; 4 char **; 2.2. Assigning to pointer variables.

  12. c

    Can I assign a pointer to an integer variable? Like the following. int *pointer; int array1 [25]; int addressOfArray; pointer = &array1 [0]; addressOfArray = pointer; Is it possible to do like this? pointers assignment-operator Share Improve this question Follow edited Sep 5, 2018 at 11:19 Lundin 201k 41 258 408 asked May 7, 2012 at 20:57

  13. Pointer declaration

    Pointer declaration is a fundamental concept in C and C++ programming. It allows the creation of variables that store the address of another variable or function. Learn how to declare, initialize, and use pointers, as well as their syntax, types, and operators. Compare pointers with other C and C++ features, such as arrays, variadic functions, and atomic references.

  14. Pointer Basics

    Versions. Below are versions of this example in C, Java, C++, and Pascal.They all do the same thing -- the syntax is just adjusted for each language. C Version. The pointers x and y are allocated as local variables. The type int* means "pointer which points to ints". As Binky learns, the pointers do not automatically get pointees.

  15. Pointers in C Explained

    1. What exactly are pointers? Before we get to the definition of pointers, let us understand what happens when we write the following code: int digit = 42; A block of memory is reserved by the compiler to hold an int value.

  16. c++

    3. Because the types don't match. The 6 itself is not a value of pointer type, it's an integer so it cannot be directly stored in a pointer. When you do *q = 6 the * dereferences the pointer, so the type becomes int (or rather an lvalue int, i.e. something that can be assigned to). Share.

  17. C Pointers for integer, float, and char

    C Pointers for int, float, and char- Explains about C pointers, to use for different data types and examples. ... chp = &i; ^ c-pointers.c:18:8: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] ip = &ch; ^ $ ./a.out Enter character: E Enter integer: 43 Enter float: 44.3 Address contained in chp: 3399891056 ...

  18. Void Pointers in C

    Void Pointers in C; Void Pointers in C. Last updated on July 27, 2020 We have learned in chapter Pointer Basics in C that if a pointer is of type pointer to int or (int *) then it can hold the address of the variable of type int only. It would be incorrect, if we assign an address of a float variable to a pointer of type pointer to int.

  19. C

    How to declare a Pointer to Pointer (Double Pointer) in C? int **pr; Here pr is a double pointer. There must be two *'s in the declaration of double pointer. Let's understand the concept of double pointers with the help of a diagram: As per the diagram, pr2 is a normal pointer that holds the address of an integer variable num.

  20. c++

    Assign int value to a pointer Ask Question Asked 10 years, 6 months ago Modified 10 years, 6 months ago Viewed 4k times -4 I need to assign an int value to a pointer, how would I do it? Below is a small example of what I want. struct { int a; } name; int temp = 3; struct name *obj = NULL; Now, I need to assign this value '3' to struct's 'a'. c++ c

  21. C++ pointer assignment

    148 I'd like to share a general technique that I used to learn how pointers work when I was starting out. If you apply it to your problem, you'll see the answer as plain as day. Get a big sheet of graph paper and lay it lengthwise on the table in front of you. This is your computer's memory. Each box represents one byte.

  22. c++

    Although reference and pointer arguments may (likely) be implemented with similar internal mechanics, a reference is not a pointer (see: What are the differences between a pointer variable and a reference variable?) and, as such, using one in lieu of the other is undefined behaviour.. Thus, a significant drawback of what you're doing in the shown code is that it produces undefined behaviour.