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.

How to Use Pointers in C Programming

If you are learning C programming, you have probably heard the term "pointer" before.

Pointers are one of the most important and powerful features of the C programming language. They allow us to manipulate memory directly, which can be very useful in many programming scenarios.

In C, a pointer is simply a variable that holds a memory address. We can think of it as a way to refer to a specific location in memory.

How to Declare a Pointer

To declare a pointer variable in C, we use the asterisk * symbol before the variable name. There are two ways to declare pointer variables in C:

Both of these declarations are equivalent and they declare a pointer variable named "p" that can hold the memory address of an integer.

However, it's important to note that if you declare multiple variables in a single statement, you need to include the asterisk before each variable name to indicate that they are all pointers. For example:

This declares three pointer variables named "p", "q", and "r" that can hold the memory address of an integer.

How to Initialize a Pointer

When we declare a pointer variable, it does not automatically point to any particular memory location. To initialize a pointer to point to a specific variable or memory location, we use the ampersand & operator to get the address of that variable.

For example, to initialize the pointer p to point to an integer variable called x , we would write:

This sets the value of p to be the memory address of x .

How to Dereference a Pointer

Once we have a pointer that points to a specific memory location, we can access or modify the value stored at that location by dereferencing the pointer.

To dereference a pointer, we use the asterisk * symbol again, but this time in front of the pointer variable itself. For example, to print the value of the integer that p points to, we would write:

What Does "Pointer to a Pointer" Mean?

A pointer can also point to another pointer variable. This is known as a "pointer to a pointer". We declare a pointer to a pointer by using two asterisks ** . For example:

Here, q is a pointer to a pointer. It points to the address of the p variable, which in turn points to the address of the x variable

How to Pass Pointers to Functions

We can pass pointers to functions as arguments, which allows the function to modify the value of the original variable passed in. This is known as "passing by reference".

To pass a pointer to a function, we simply declare the function parameter as a pointer. For example:

Here, the increment function takes a pointer to an integer ( int *p ) and increments the value of the integer by one ( (*p)++ ).

In main() , we declare the integer x and a pointer p that points to x . We then call the increment function, passing in the p pointer. After the function call, x has been incremented to 43 .

How to Use Pointers for Dynamic Memory Allocation

One of the most powerful uses of pointers in C is for dynamic memory allocation. This allows us to allocate memory at runtime, rather than at compile time.

We use the malloc function to dynamically allocate memory, and it returns a pointer to the allocated memory. For example:

Here, p is a pointer to an integer that has been allocated using malloc . The sizeof operator is used to determine the size of an integer in bytes.

After allocating memory, we can use the pointer variable like any other pointer. When we are finished with the memory, we should free it using the free function. For example:

This frees up the memory that was allocated to p .

What is Pointer Casting?

Sometimes you may need to cast a pointer from one type to another. You can do this using the (type *) syntax. For example:

Here, p is cast to a pointer to a double type.

How Does Pointer Arithmetic Work?

Because pointers hold memory addresses, we can perform arithmetic operations on them to move them to different memory locations.

For example, we can increment a pointer to move it to the next memory location. This is often used in array operations, where we use a pointer to access elements of an array.

For example, to print the first element of an integer array using a pointer, we could write:

Here, p is set to point to the first element of the arr array, and *p dereferences the pointer to get the value of the first element (which is 1 ).

How to Use Pointer Arrays

We can also declare arrays of pointers in C. For example:

This declares an array of three pointers to integers. Each element of the array can point to a separate integer variable.

Pointer Arithmetic and Arrays

We can use pointer arithmetic to access elements of an array. For example:

Here, p is set to point to the first element of the arr array. We can use pointer arithmetic to access the second element of the array ( *(p + 1) ), which is 2 .

Example of How to Use Pointers

Here's an example program that demonstrates some of the concepts we've discussed:

Screenshot-from-2023-05-01-12-03-41

This program demonstrates several concepts related to pointers.

First, we declared an integer variable x and a pointer p that points to x . We called the increment function, passing in the p pointer. The increment function modifies the value of x by incrementing it by one. We then printed the value of x before and after the function call to demonstrate that x has been incremented.

Next, we used dynamic memory allocation to allocate an array of three integers. We set the values of the array elements using pointer arithmetic ( arr[0] = 1 , arr[1] = 2 , etc.). We then declared a pointer q that points to the first element of the array. Furthermore, we used pointer arithmetic to access and print the values of each element of the array.

Finally, we freed the memory that was allocated to the array using the free function.

This program demonstrates how pointers can be used to modify the value of a variable, access elements of an array using pointer arithmetic, and dynamically allocate and free memory.

Common Pointer Errors

Pointers can be tricky to work with, and they can lead to some common errors.

One common error is using an uninitialized pointer. If you declare a pointer variable but do not initialize it to point to a valid memory location, you may get a segmentation fault or other error when you try to dereference the pointer.

Another common error is dereferencing a null pointer, which can also cause a segmentation fault.

Another error to be aware of is using the wrong type of pointer. For example, if you declare a pointer to an integer but then try to dereference it as a pointer to a character, you may get unexpected results or errors.

Pointers are a powerful tool in C programming, but they can be a bit tricky to work with. With practice and patience, you can master pointers and use them to manipulate memory and work with complex data structures.

Thank you for reading!

A curious full-stack web developer. I love solving problems using software development and representing Data in a meaningful way. I like pushing myself and taking up new challenges.

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 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

Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn’t store any value. 

Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These operations are:

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

1. Increment/Decrement of a Pointer

Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. 

For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 4( size of an int ), and the new address will point to 1004 . While if a float type pointer is incremented then it will increment by 4( size of a float ) and the new address will be 1004 .

Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. 

For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement by 4( size of an int ), and the new address will point to 996 . While if a float type pointer is decremented then it will decrement by 4( size of a float ) and the new address will be 996 .

pointer increment and decrement

Note: It is assumed here that the architecture is 64-bit and all the data types are sized accordingly. For example, integer is of 4 bytes.

Example of Pointer Increment and Decrement

Below is the program to illustrate pointer increment/decrement:

Note: Pointers can be outputted using %p, since, most of the computers store the address value in hexadecimal form using %p gives the value in that form. But for simplicity and understanding we can also use %u to get the value in Unsigned int form.

2. Addition of Integer to Pointer

When a pointer is added with an integer value, the value is first multiplied by the size of the data type and then added to the pointer.

For Example: Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

pointer addition

Example of Addition of Integer to Pointer

3. subtraction  of integer to pointer.

When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type and then subtracted from the pointer similar to addition.

For Example: Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

pointer substraction

Example of Subtraction of Integer from Pointer

Below is the program to illustrate pointer Subtraction:

4. Subtraction of Two Pointers

The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. 

For Example:   Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is given by (4/4) = 1 .

Example of Subtraction of Two Pointer

Below is the implementation to illustrate the Subtraction of Two Pointers:

5. Comparison of Pointers

We can compare the two pointers by using the comparison operators in C. We can implement this by using all operators in C >, >=, <, <=, ==, !=.   It returns true for the valid condition and returns false for the unsatisfied condition. 

  • Step 1: Initialize the integer values and point these integer values to the pointer.
  • Step 2: Now, check the condition by using comparison or relational operators on pointer variables.
  • Step 3: Display the output.

Example of Pointer Comparision

Comparison to null.

A pointer can be compared or assigned a NULL value irrespective of what is the pointer type. Such pointers are called NULL pointers and are used in various pointer-related error-handling methods.

Comparison operators on Pointers using an array

In the below approach, it results in the count of odd numbers and even numbers in an array. We are going to implement this by using a pointer.

  • Step 1: First, declare the length of an array and array elements.
  • Step 2: Declare the pointer variable and point it to the first element of an array.
  • Step 3: Initialize the count_even and count_odd. Iterate the for loop and check the conditions for the number of odd elements and even elements in an array
  • Step 4: Increment the pointer location ptr++ to the next element in an array for further iteration.
  • Step 5: Print the result.

Example of Pointer Comparison in Array

Pointer arithmetic on arrays.

Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element.

For Example: if an array is named arr then arr and &arr[0] can be used to reference the array as a pointer.

Below is the program to illustrate the Pointer Arithmetic on arrays:

Program 1:  

Program 2:  

Please Login to comment...

  • C-Advanced Pointer
  • C-Pointer Basics
  • keerthikarathan123
  • simmytarika5
  • surinderdawra388
  • lathnishtha775
  • abhishekcpp

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

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

  • Overview of C
  • Features of C
  • Install C Compiler/IDE
  • My First C program
  • Compile and Run C program
  • Understand Compilation Process
  • C Syntax Rules
  • Keywords and Identifier
  • Understanding Datatypes
  • Using Datatypes (Examples)
  • What are Variables?
  • What are Literals?
  • Constant value Variables - const
  • C Input / Output
  • Operators in C Language
  • Decision Making
  • Switch Statement
  • String and Character array
  • Storage classes

C Functions

  • Introduction to Functions
  • Types of Functions and Recursion
  • Types of Function calls
  • Passing Array to function

C Structures

  • All about Structures
  • Pointers concept
  • Declaring and initializing pointer
  • Pointer to Pointer
  • Pointer to Array
  • Pointer to Structure
  • Pointer Arithmetic
  • Pointer with Functions

C File/Error

  • File Input / Output
  • Error Handling
  • Dynamic memory allocation
  • Command line argument
  • 100+ C Programs with explanation and output

Using Pointers in C

In this tutorial, we will learn how to declare, initialize and use a pointer in C language .

Before you continue, check these topics out:

Introduction to Pointers

C Loops - while , do while , for loops

A pointer is a variable used to store memory address. Hence, we have to declare and initialise(assign it a value) it just like any other variable. Pointers can be very useful in some use-cases, like:

  • They make accessing array elements easier.
  • We can implement linked lists, trees, and graphs using pointers.
  • We use pointers for accessing dynamically allocated memory.
  • We can return more than one value from a function using pointers.

So let's see how we can create pointers, assign values to pointers, perform pointer coversions, pointer arithmetic and pointer comparisons.

Declaring a Pointer in C

The general syntax of pointer declaration is,

Here, pointer_name is the name of the pointer and that should be a valid C identifier .

The datatype of the pointer and the variable to which the pointer variable is pointing must be the same.

Following are some examples of declaring a pointer in C:

Just like a variable, pointer is declared in the same way, just with an additional pointer operator * .

Assigning Value to a Pointer Variable

When we declare a pointer, it contains garbage value , which means it could be pointing anywhere in the memory. Pointer Initialization is the process of assigning the address of a variable to a pointer. In C language, the address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it.

For example,

Value at ptr is: 10 Address pointed by ptr is: 0x7fff99c0e6c4

Run Code →

initialize pointer variable in C

Pointer variables must always point to variables of the same datatype.

For example, if we have a float type variable and an int type pointer, then C compiler will give error.

warning: assignment from incompatible pointer type ptr = &x; ^

While declaring a pointer variable, if it is not assigned to anything then it contains garbage value . And that can lead to unexpected errors in your program. Hence, it is recommended to assign a NULL value to it.

When we assign NULL to a pointer, it means that it does not point to any valid address. NULL denotes the value 'zero'.

set pointer variable value

A pointer that is assigned a NULL value is called a NULL pointer in C .

We can give a pointer a null value by assigning it zero to it. For example,

The above code will initialize the ptr pointer will a null value.

We can also use the NULL macro, which is nothing but a predefined constant for null pointer. This is defined in the <stdio.h> header library.

Pointer to Pointer Assignment in C

We can use an assignment operator to assign value of a pointer to another pointer variable. But for such assignment, types of both the pointer should be same.

Let's take a code example,

Value at p1 and p2: 10 10 Address pointed by p1 and p2: 0x7fff99c0e6c4 0x7fff99c0e6c4

As you can see in the code example above, multiple pointers can point to the same variable but they should be of the same data type.

Pointer Type Conversion in C

1. void * pointer.

The pointers of type void * are known as Generic pointers , and they can be assigned to any other type of pointer. Also, any other type of pointer can be assigned to a void * pointer.

2. Pointer type conversion

For pointer type other than void * , we have to explicitly cast pointer from one type to another. But this can lead to unexpected behaviour for incompatible datatypes.

For example, if we have a variable of type double , and we want to use a pointer of type int to point to this variable. Even after using explicit cast, the pointer will work as if it is pointing to a int type value. Now, a double type is of 8 bytes whereas an int type is of 4 bytes , hence, 4 bytes of information will be lost.

Let's see how we can use explicit cast for pointer conversion.

Value of a is: -858993459.000000

Pointer and Arrays

Derefrencing pointer in c.

Once a pointer has been assigned the address of a variable, the pointer is dereferenced , using the indirection operator or dereferencing operator , which is a * , to access the value of the variable.

For example, if we have,

Here is one complete program,

10 10 3795480300 3795480300 3795480304

Points to Remember while using Pointers

A pointer variable stores the address of a variable. We use * to declare and identify a pointer.

We can find the address of any variable using the & (ampersand) operator.

The declaration int *a doesn't mean that a is going to contain an integer value. It means that a is going to contain the address of a variable of int type.

We can dereference a pointer variable using a * operator. Here, the * can be read as 'value at' .

Since you have now learned the basics of Pointers in C, you can check out some C Pointer Programs where pointers are used for different use-cases.

Simple Pointer Program

Array of Pointer Program

What is Double Pointer?

Pointer with Function

  • ← Prev
  • Next →

7.0 Pointers

7.1.0 pointer basics.

int i = 5; ip = &i;
ip = &i;
*ip = &i;
int i = 5; int *ip; ip = &i; // Point ip to the memory address of variable i. *ip = 10; // Change the contents of the variable ip points to to 10.

7.2.0 Pointers and Arrays - Pointer Arithmetic

int a[10]; int *pa = &a[0];
int a[10]; int *pa = a;
int a[10]; int *pa = &a[4];
int a[10]; int *pa = a+4; // Converts to &a[0] + 4 or &a[4]
int a[5] = {1,2,3,4,5}; int *pa = a; int i, total = 0; for(i = 0; i
int a[5] = {1,2,3,4,5}; int *pa = a; pa = pa+3; // Increments the pointer by 3 *pa = *pa+3 // WRONG: Increments the contents of the variable // pointed to by pa by 3

7.3.0 Pointers as function arguments

char function(char a[]); char function(char *a);
void function (char a[], int len) { int k; for(k = 0; k

assign pointer to integer in c

  • Website Rank
  • ASP.net Examples
  • EMI Calculator

assign pointer to integer in c

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

DevsENV

  • C Programming

Pointer in C Programming Language with Practical Examples

  • Conceptual View of a Variable in Memory
  • Declaration of Pointer
  • Initialization of Pointer
  • Dereferencing Pointer
  • Null Pointers
  • Void Pointers
  • Regular Pointers
  • Function Pointers
  • Pointer to Pointer
  • Addition and Subtraction
  • Comparison of Pointers of Same Types
  • More Examples

In C programming, a Pointer variable stores memory address of another variable, pointing to where other variable resides in memory. Pointer variables Provide direct access and manipulation of memory, enhancing code flexibility and efficiency.

¶ Conceptual View of a Variable in Memory

Every variable is assigned a specific memory location, allowing the program to store and retrieve data. This memory can be conceptualized as a contiguous sequence of bytes, each with a unique address. Let’s see how an variable is stored inside memory.

Representation of a Variable in Memory in C programming

Here, an integer variable var stores 13 at memory location 1001 and pointer variable ptr stores the memory location 1001 of var .

Though different data types require different amounts of memory to store a variable, all pointer variables require the same amount of memory for the memory address. The size of a memory address is architecture-dependent, with 64-bit architectures requiring 8 bytes , and 32-bit architectures requiring 4 bytes .

¶ Declaration of Pointer

The declaration of a pointer involves specifying the data type it points to, followed by an asterisk (*) known as dereference operator. This asterisk indicates that the variable is a pointer.

¶ Initialization of Pointer

Pointers can be initialized by assigning the memory address of a variable to them. The address-of operator (&) is used for this purpose.

Here, when we assign &var to a pointer variable ptr it stores the memory address ( 1001 ) of the variable. Now, we can indirectly manipulate data in the address 1001 through ptr .

¶ Dereferencing Pointer

Dereferencing a pointer is accomplished using the dereference operator *. This operator, when applied to a pointer, retrieves the value stored at the memory address pointed to by that pointer.

When we print value in ptr it prints a memory location in hexadecimal as it stores a memory location. But when we dereference it with * it prints the value in the memory location stored in it.

¶ Types of Pointers in C Programming

Depending on the types of data that pointer variables point to, they are mainly classified as follows,

¶ Null Pointers

A null pointer is a pointer that does not point to any memory location. It is often used to indicate the absence of a valid memory address. In C, a null pointer is represented by assigning the value NULL to a pointer.

¶ Void Pointers

Void pointers, or generic pointers, are pointers that can point to objects of any data type. They can be casted to different types according to need. Thus, providing a way to achieve flexibility in handling different data types without explicitly specifying the type. But they can not be dereferenced.

¶ Regular Pointers

They are the pointers that point to specific data types like int, char, or float. These pointers are essential for efficiently manipulating and accessing individual elements of basic data types. Examples we have seen so far are mostly of this type.

¶ Function Pointers

Function pointers point to functions instead of data. They are particularly useful in scenarios where different functions need to be called based on certain conditions. They actually point to the code segment in the memory of the function it is pointing to, allowing the execution of the function through the pointer.

¶ Pointer to Pointer

A pointer to a pointer, also known as a multilevel pointer, stores the address of another pointer. This type of pointer is especially useful in dynamic memory allocation and multidimensional arrays.

¶ Pointer Arithmetic

Pointer arithmetic is different from other variables. Pointer arithmetic supports following operations,

¶ Addition and Subtraction

Adding or subtracting an integer value to a pointer results in moving in memory by a distance calculated based on the size of the data type the pointer points to. For integers, pointers move 4 bytes.

¶ Comparison of Pointers of Same Types

We cam compare two pointers of the same type using relational operators. When comparing pointers, you are comparing the memory addresses they hold.

¶ More Examples

  • Print an Array Using Pointer
  • Swap Two Numbers using Pointers

All Tutorials in this playlist

What is C Programming and How to Start C Programming

What is C Programming and How to Start C Programming

Getting Started Your First Coding With C Programming

Getting Started Your First Coding With C Programming

Variable and Data Types with Practical Examples in C Programming

Variable and Data Types with Practical Examples in C Programming

Input and Output in C Programming

Input and Output in C Programming

Conditional in C Programming - if-else, elseif, switch-case

Conditional in C Programming - if-else, elseif, switch-case

Loops in C Programming - for loop, while loop and do-while loop

Loops in C Programming - for loop, while loop and do-while loop

Functions in C Programming - with Practical examples

Functions in C Programming - with Practical examples

Arrays in C Programming - Algorithm and Practical examples

Arrays in C Programming - Algorithm and Practical examples

Recursion in C Programming Language with Practical Examples

Recursion in C Programming Language with Practical Examples

Structure in C Programming Language with practical examples

Structure in C Programming Language with practical examples

File Handling in C Programming Language with Practical Examples

File Handling in C Programming Language with Practical Examples

Pointer in C Programming Language with Practical Examples

Student Management Complete Application Using C Programming

C Project - Complete Calculator Application using C Programming

C Project - Complete Calculator Application using C Programming

Popular tutorials, vue js 3 - complete advance crud example with vuex, vue-validate, pagination, searching and everything, laravel eloquent vs db query builder [performance and other statistics], laravel role permission management system full example with source code, start wordpress plugin development with react js easily in just few steps, laravel membership management full project demo with source codes, connect your react app with websocket to get real time data, numerical methods for engineers ebook & solution download - download pdf, #ajax with laravel api and more - learn laravel beyond the limit, laravel ecommerce complete web application with admin panel, what is seeder in laravel and why we need it.

  • Bash Scripting

Bootstrap CSS

  • Code Editor
  • Computer Engineering
  • Data Structure and Algorithm

Design Pattern in PHP

Design Patterns - Clean Code

  • Git Commands

Interview Prepration

Java Programming

Laravel PHP Framework

Online Business

  • Programming

React Native

Rust Programming

Tailwind CSS

Uncategorized

Windows Operating system

  • Woocommerce

WordPress Development

  • C-sharp programming
  • Design pattern
  • Mathematics
  • Rust Programming Language
  • Windows terminal
  • WordPress Plugin Development

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)

assign pointer to integer in c

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

IMAGES

  1. Expressions de pointeur en C avec exemples

    assign pointer to integer in c

  2. C/C++ 中的指针与示例

    assign pointer to integer in c

  3. Pointer Expressions in C with Examples

    assign pointer to integer in c

  4. Pointers in C and C++

    assign pointer to integer in c

  5. Functions Pointers in C Programming with Examples

    assign pointer to integer in c

  6. Pointers in C

    assign pointer to integer in c

VIDEO

  1. C++

  2. C Programming Structure and Pointer

  3. C++ pointers part1 sec10_1

  4. Arrays of pointers in C

  5. Arrays and Pointers in C Lec- 21

  6. Excel VBA CLngPtr CONVERT TO LONG INTEGER POINTER

COMMENTS

  1. c

    Assigning a pointer to an integer Ask Question Asked 11 years, 8 months ago Modified 1 year, 2 months ago Viewed 25k times 5 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

  2. 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;

  3. 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.

  4. Pointers in C

    Menu Fundamentals C Programming Data Structures 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.

  5. 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.

  6. INT36-C. Converting a pointer to integer or integer to pointer

    Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

  7. How to Use Pointers in C Programming

    To initialize a pointer to point to a specific variable or memory location, we use the ampersand & operator to get the address of that variable. For example, to initialize the pointer p to point to an integer variable called x, we would write: int x = 42; int *p = &x; This sets the value of p to be the memory address of x.

  8. Pointer Arithmetics in C with Examples

    Note: Pointers can be outputted using %p, since, most of the computers store the address value in hexadecimal form using %p gives the value in that form. But for simplicity and understanding we can also use %u to get the value in Unsigned int form. 2. Addition of Integer to Pointer. When a pointer is added with an integer value, the value is first multiplied by the size of the data type and ...

  9. Pointer Basics

    You can assign 0 into a pointer: ptr = 0; The null pointer is the only 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!

  10. Pointer Basics

    The type int* means "pointer which points to ints". As Binky learns, the pointers do not automatically get pointees. ... Dereference each pointer to access the .next field in its pointee, and use pointer assignment to set the .next field to point to the appropriate Node. C Code Java Code { // Allocate the pointers struct Node* x; struct Node* y ...

  11. 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.

  12. Pointers in C Programming with examples

    #include <stdio.h> int main() { //Variable declaration int num = 10; //Pointer declaration int *p; //Assigning address of num to the pointer p p = # printf("Address of variable num is: %p", p); return 0; } Output: Address of variable num is: 0x7fff5694dc58 C Pointers - Operators that are used with Pointers

  13. c

    How can I assign the value to pointer? Ask Question Asked 5 years, 7 months ago Modified 5 years, 7 months ago Viewed 3k times 0 I was studying the data structure in C programming. and I got a question of pointer. there is a simple initialization of pointer variable head. int* head = NULL;

  14. Using Pointers in C

    The general syntax of pointer declaration is, type *pointer_name; Here, pointer_name is the name of the pointer and that should be a valid C identifier. The datatype of the pointer and the variable to which the pointer variable is pointing must be the same. Following are some examples of declaring a pointer in C: int *ptr; //pointer to int ...

  15. 7.0 Pointers

    To assign a pointer to the array we can use the following declaration... int a[10]; int *pa = &a[0]; Basically this assigns the memory address of a[0] the first element in array a to pointer of type int. Incrementing the pointer, pa++, moves it to the next block of memory which would be the second element of the array a, &a[1]. One thing you ...

  16. C Pointers for integer, float, and char

    Need to declare a pointer before using it to store any variable address. Let us consider below decalration, int a = 25; int *b; b = &a; 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.

  17. Pointer in C Programming Language with Practical Examples

    Pointers can be initialized by assigning the memory address of a variable to them. The address-of operator (&) is used for this purpose. int var = 15; int *ptr = &var; Here, when we assign &var to a pointer variable ptr it stores the memory address ( 1001) of the variable. Now, we can indirectly manipulate data in the address 1001 through ptr.

  18. How to assign a integer to a pointer in c?

    1 The task is to create a function int* pairSumSearch (int* data, int numEls, int pairSum) that searches within the first numEls of a list if ints 'data', to find two adjacent integers that sum to 'pairSum' and return a pointer to the position of the first of the two integers.

  19. Converting Int to Pointer in C

    Blog Converting Int to Pointer in C Sai A Updated date Oct 29, 2023 In this blog, we will explore how to cast or convert integers to pointers in C. The program demonstrates three methods, including explicit casting and the use of intptr_t, accompanied by detailed explanations. 738 0 0 C Int Integer Programming

  20. C++ pointer assignment

    11 Answers Sorted by: 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.

  21. C++ Assign Pointer to Pointer

    For the pointer assignment question, you can directly assign: int *ptr2 = ptr2; in your second example, provided you make sure ptr1 points at a valid location. For example, int x; int *ptr1 = &x; /* ptr1 now points to the address of x */ *ptr1 = 7; int *ptr2; ptr1 = ptr2; Share

  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.