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 language assign value to pointer

  • Book:C Programming

Navigation menu

Precedence and Associativity

Pointers and arrays, pointers and strings, pointers and functions, pointers and structures, handling files, command line arguments, dynamic memory allocation, c - pointers and variables.

C Programming

c language assign value to pointer

In this tutorial we will learn to manipulate variables using pointers in C programming language.

We already know from the Pointers tutorial how to create a pointer variable and store address of a variable in it.

Now let us go ahead and create an integer int variable and manipulate it via an integer pointer variable ptr .

Creating an integer variable

This is fairly simple. All we have to do is declare a variable using the int data type.

Three things will happen for the above line of code.

  • A memory location is located to store integer value.
  • The value 10 is saved in that memory location.
  • We can refer the memory location using the variable name num .

Creating integer pointer variable

Now we will create an integer pointer variable ptr that will store the address of the integer variable num .

To get the address of a variable we use the address of & operator.

We can represent the integer variable num and pointer variable ptr as follows.

c language assign value to pointer

So, we can see that variable num was allocated memory location 8280 (which will change the next time the program is executed). In that location value 10 was stored.

Similarly, variable ptr was allocated memory location 8272 and it holds the value 8280 which is the memory location of variable num . So, ptr is pointing at the num variable.

Accessing value of a variable via pointer

To access the value stored in the variable num via the pointer variable ptr we have to use the value at the address of * operator.

We already have the address of variable num stored in variable ptr . So, using *ptr will give use the value stored at the address i.e., value stored in num variable.

Updating the value of a variable via pointer

To update the value of a variable via pointer we have to first get the address of the variable and then set the new value in that memory address.

We get the address via address of & operator and then we set the value using the value at the address of * operator.

Complete code:

© 2014 - 2023 dyclassroom . All rights reserved.

c language assign value to pointer

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

c language assign value to pointer

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Python questions
  • View PHP questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

Assign new value to pointer in C

c language assign value to pointer

3 solutions

  • Most Recent

c language assign value to pointer

Add your solution here

  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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


  1. A Brief Introduction to Pointers in C++

    c language assign value to pointer

  2. Pointers in C Programming with examples

    c language assign value to pointer

  3. Pointers in C/C++ (with examples)

    c language assign value to pointer

  4. Pointer in C : basics, pointer to variable, passing pointer to function

    c language assign value to pointer

  5. [key and difficult points of C language] C language pointer

    c language assign value to pointer

  6. “malloc” in C

    c language assign value to pointer


  1. 2. "C" Pointers and Expressions

  2. C++

  3. C LANGUAGE in Telugu Part-3 (POINTERS & FUNCTIONS) || POINTERS|| FUNCTIONS || C Programming తెలుగులో

  4. C++ Pointer Part 2

  5. Variables in ActionScript

  6. C++ pointers part2 sec10_2


  1. What Are RVU Values by CPT Code?

    A relative value unit based on a Current Procedural Terminology code assigns a standard work value based on a medical procedure performed by health care providers, according to Advancing the Business of Healthcare. The RVU represents the co...

  2. What Are the Baseball Cards with the Highest Values of All Time?

    Baseball cards were first printed in the 1860s, but their first surge in widespread popularity didn’t occur until the turn of the 20th century. PSA, a world-renowned third-party authentication company, assigns a grade of 1 to 10 in determin...

  3. What Is a Cultural Narrative?

    Cultural narratives are stories that help a community structure and assign meaning to its history and existence. Cultural narratives include creation stories, which tell a story about the community’s origins, and fables, which help teach mo...

  4. Directly assigning values to C Pointers

    Cause that pointer is not initialized - it may point to pretty much anywhere and might crash the program. · You got lucky that it terminated with

  5. C Programming/Pointers and arrays

    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 '

  6. How can I assign value to a pointer variable in C?

    In C, a pointer variable can be assigned a value by setting it to the address of another variable using the address-of operator & . Once a

  7. C

    To update the value of a variable via pointer we have to first get the address of the variable and then set the new value in that memory address. We get the

  8. [Solved] Assign new value to pointer in C

    I wanted to make a function that takes a pointer to integer as a parameter, and sets the value to 0 in c programming language.But I do not know

  9. C Pointers

    Pointer initialization is the process where we assign some initial value to the pointer variable. ... In C programming language, pointers and

  10. C Pointers (With Examples)

    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.

  11. 10.1 Basic Pointer Operations

    This works for one pointer, because C essentially ignores whitespace. But if

  12. 1. Pointer Variables

    // Assign a value to where the pointer is pointed to, NOT to the pointer

  13. Pointer Basics

    This is the best way to attach a pointer to an existing variable: int * ptr; // a pointer int num; // an integer ptr = # // assign the address of num into

  14. Assigning values to C pointers using direct declaration

    Directly declare and assign value to C pointers, Assign value to a pointer, Unable to assign value in variable of Structure in C using