C Programming Tutorial

  • Pointers and 2-D arrays

Last updated on July 27, 2020

In the last chapter, we have created a pointer which points to the 0th element of the array whose base type was ( int * ) or pointer to int . We can also create a pointer that can point to the whole array instead of only one element of the array. This is known as a pointer to an array. Here is how you can declare a pointer to an array.

Here p is a pointer that can point to an array of 10 integers. In this case, the type or base type of p is a pointer to an array of 10 integers.

Note that parentheses around p are necessary, so you can't do this:

here p is an array of 10 integer pointers. An array of pointers will be discussed in upcoming chapters.

A pointer that points to the 0th element of an array and a pointer that points to the whole array are totally different. The following program demonstrates this concept.

Expected Output:

How it works:

Here p is a pointer which points to the 0th element of the array my_arr , while parr is a pointer which points to the whole array my_arr . The base type of p is of type ( int * ) or pointer to int and base type of parr is pointer to an array of 5 integers. Since the pointer arithmetic is performed relative to the base type of the pointer, that's why parr is incremented by 20 bytes i.e ( 5 x 4 = 20 bytes ). On the other hand, p is incremented by 4 bytes only.

The important point you need to remember about pointer to an array is this:

Whenever a pointer to an array is dereferenced we get the address (or base address) of the array to which it points.

So, on dereferencing parr , you will get *parr . The important thing to notice is although parr and *parr points to the same address, but parr's base type is a pointer to an array of 5 integers, while *parr base type is a pointer to int. This is an important concept and will be used to access the elements of a 2-D array.

Pointers and 2-D Array #

While discussing 2-D array in the earlier chapters, we told you to visualize a 2-D array as a matrix. For example:

The above 2-D array can be visualized as following:

assign pointer to 2d array in c

While discussing array we are using terms like rows and column. Well, this concept is only theoretical, because computer memory is linear and there are no rows and cols. So how actually 2-D arrays are stored in memory ? In C, arrays are stored row-major order. This simply means that first row 0 is stored, then next to it row 1 is stored, next to it row 2 is stored and so on.

The following figure shows how a 2-D array is stored in the memory.

assign pointer to 2d array in c

Here is the most important concept you need to remember about a multi-dimensional array.

A 2-D array is actually a 1-D array in which each element is itself a 1-D array. So arr is an array of 3 elements where each element is a 1-D array of 4 integers.

In the previous chapter, we have already discussed that the name of a 1-D array is a constant pointer to the 0th element. In the case, of a 2-D array, 0th element is a 1-D array. Hence in the above example, the type or base type of arr is a pointer to an array of 4 integers. Since pointer arithmetic is performed relative to the base size of the pointer. In the case of arr , if arr points to address 2000 then arr + 1 points to address 2016 (i.e 2000 + 4*4 ).

We know that the name of the array is a constant pointer that points to the 0th element of the array. In the case of a 2-D array, 0th element is a 1-D array. So the name of the array in case of a 2-D array represents a pointer to the 0th 1-D array. Therefore in this case arr is a pointer to an array of 4 elements. If the address of the 0th 1-D is 2000 , then according to pointer arithmetic ( arr + 1 ) will represent the address 2016 , similarly ( arr + 2 ) will represent the address 2032 .

From the above discussion, we can conclude that:

arr points to 0th 1-D array. (arr + 1) points to 1st 1-D array. (arr + 2) points to 2nd 1-D array.

assign pointer to 2d array in c

In general, we can write:

(arr + i) points to ith 1-D array.

As we discussed earlier in this chapter that dereferencing a pointer to an array gives the base address of the array. So dereferencing arr we will get *arr , base type of *arr is (int*) . Similarly, on dereferencing arr+1 we will get *(arr+1) . In general, we can say that:

*(arr+i) points to the base address of the ith 1-D array.

Again it is important to note that type (arr + i) and *(arr+i) points to same address but their base types are completely different. The base type of (arr + i) is a pointer to an array of 4 integers, while the base type of *(arr + i) is a pointer to int or ( int* ).

So how you can use arr to access individual elements of a 2-D array?

Since *(arr + i) points to the base address of every ith 1-D array and it is of base type pointer to int , by using pointer arithmetic we should we able to access elements of ith 1-D array.

Let's see how we can do this:

*(arr + i) points to the address of the 0th element of the 1-D array. So, *(arr + i) + 1 points to the address of the 1st element of the 1-D array *(arr + i) + 2 points to the address of the 2nd element of the 1-D array

Hence we can conclude that:

*(arr + i) + j points to the base address of jth element of ith 1-D array.

On dereferencing *(arr + i) + j we will get the value of jth element of ith 1-D array.

By using this expression we can find the value of jth element of ith 1-D array.

Furthermore, the pointer notation *(*(arr + i) + j) is equivalent to the subscript notation.

The following program demonstrates how to access values and address of elements of a 2-D array using pointer notation.

Assigning 2-D Array to a Pointer Variable #

You can assign the name of the array to a pointer variable, but unlike 1-D array you will need pointer to an array instead of pointer to int or ( int * ) . Here is an example:

Always remember a 2-D array is actually a 1-D array where each element is a 1-D array. So arr as an array of 2 elements where each element is a 1-D arr of 3 integers. Hence to store the base address of arr , you will need a pointer to an array of 3 integers.

Similarly, If a 2-D array has 3 rows and 4 cols i.e int arr[3][4] , then you will need a pointer to an array of 4 integers.

Here p is a pointer to an array of 3 integers. So according to pointer arithmetic p+i points to the ith 1-D array, in other words, p+0 points to the 0th 1-D array, p+1 points to the 1st 1-D array and so on. The base type of ( p+i ) is a pointer to an array of 3 integers. If we dereference ( p+i ) then we will get the base address of ith 1-D array but now the base type of *(p + i) is a pointer to int or ( int * ). Again to access the address of jth element ith 1-D array, we just have to add j to *(p + i) . So *(p + i) + j points to the address of jth element of ith 1-D array. Therefore the expression *(*(p + i) + j) gives the value of jth element of ith 1-D array.

The following program demonstrates how to access elements of a 2-D array using a pointer to an array.

Load Comments

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

Recent Posts

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

Codeforwin

How to access two dimensional array using pointers in C programming?

How to access two dimensional array using pointers in C programming? Write a C program to input and print elements of a two dimensional array using pointers and functions.

Required knowledge

Multi-dimensional array , Pointers , Pointers and Arrays , Functions

How to access two dimensional array using pointers?

To access a two dimensional array using pointer, let us recall basics from one dimensional array . Since it is just an array of one dimensional array.

Suppose I have a pointer array_ptr pointing at base address of one dimensional array. To access nth element of array using pointer we use *(array_ptr + n) (where array_ptr points to 0th element of array, n is the nth element to access and nth element starts from 0).

Now we know two dimensional array is array of one dimensional array. Hence let us see how to access a two dimensional array through pointer.

Let us suppose a two-dimensional array

For the above array,

Note: If you are not familiar with *(matrix + 2) syntax then please give yourself time and learn pointer arithmetic in C .

Two dimensional array access using pointer

Program to access a two dimensional array using pointer

Note: You can use any of the two notations int matrix[][COLS] or int (*matrix)[COLS] , to access two dimensional array using pointers. The first int matrix[][COLS] is general array notation. Whereas int (*matrix)[COLS] is a pointer to array.

Recommended posts

  • Array and matrix programming exercises index .
  • C program to sort array using pointers .
  • C program to search an element in array using pointers .
  • C program to reverse an array using pointers .
  • C program to swap two arrays using pointer .
  • C program to copy one array to another using pointers .

Precedence and Associativity

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

assign pointer to 2d array in c

C - Pointers and Two Dimensional Array

C Programming

In this tutorial we will learn to work with two dimensional arrays using pointers in C programming language.

In the previous tutorial Pointers and One Dimensional Array we learned to work with one dimensional character array. Feel free to checkout that tutorial.

Creating a two dimensional array

To keep things simple we will create a two dimensional integer array num having 3 rows and 4 columns.

assign pointer to 2d array in c

In the above image we are showing the two dimensional array having 3 rows and 4 columns.

The compiler will allocate the memory for the above two dimensional array row-wise meaning the first element of the second row will be placed after the last element of the first row.

assign pointer to 2d array in c

And if we assume that the first element of the array is at address 1000 and the size of type int is 2 bytes then the elements of the array will get the following allocated memory locations.

assign pointer to 2d array in c

Create pointer for the two dimensional array

We have created the two dimensional integer array num so, our pointer will also be of type int .

We will assign the address of the first element of the array num to the pointer ptr using the address of & operator.

Accessing the elements of the two dimensional array via pointer

The two dimensional array num will be saved as a continuous block in the memory. So, if we increment the value of ptr by 1 we will move to the next block in the allocated memory.

In the following code we are printing the content of the num array using for loop and by incrementing the value of ptr .

Address mapping

We can compute the address of an element of the array by using the rows and columns of the array. For this we use the following formula.

Where, arr is a two dimensional array. i and j denotes the ith row and jth column of the array.

baseAddress denotes the address of the first element of the array. And no_of_cols is the total number of columns in the row.

And size_of_data_type is the size of the type of the pointer. If the type is int then size_of_data_type = 2 bytes and if the type is char then size_of_data_type = 1 bytes.

For example, in the case of num array the baseAddress = 1000, no_of_cols = 4 and size_of_data_type = 2.

So, we can compute the memory address location of the element num[2][3] as follows.

Accessing the value of the two dimensional array via pointer using row and column of the array

If we want to get the value at any given row, column of the array then we can use the value at the address of * operator and the following formula.

Where, arr is a two dimensional array and i and j denotes the ith row and jth column of the array.

ptr holds the address of the first element of the array.

And no_of_cols denotes the total number of column in the row of the array.

In the following example we are finding the value at the location 2nd row and 3rd column of the array num .

Complete code

© 2014 - 2024 dyclassroom . All rights reserved.

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

assign pointer to 2d array in c

  • Book:C Programming

Navigation menu

Aticleworld

Aticleworld

Aticleworld offer c tutorial,c programming,c courses, c++, python, c#, microcontroller,embedded c, embedded system, win32 api, windows and linux driver, tips, how to access two dimensional array using pointers in c.

How to access two dimensional array using pointers in C

I have written a lot of articles on array and pointer if you want you can see this link, C Tutorial . Nowadays many students ask me a question that how to access a multidimensional array with a pointer in C or access two dimensional array using pointers in C I have replied many students but every month I found this question in my Inbox.

So I have decided to write an article on how to access a multidimensional array with a pointer (Access two-dimensional array using pointers in C). I am assuming you are already familiar with a multidimensional array, if you don’t have the knowledge of array, then you should check this article, brief introduction of an array .

Relationship between array and pointer

In C-language pointer and array are very close to each other, an array can be split in the form of the pointer. The name of the array is a pointer to its first element. So if acData is an array of character then acData will be the address of its first element. You can also say that acData is similar to the &acData[0]

Below expression describe a relation between array and pointer,

Note Array elements stored in a consecutive memory block, so we can access the elements of the array using the pointer.

Access a 2d array using a single pointer

In C language, the compiler calculates offset to access the element of the array. The calculation of the offset depends on the array dimensions.

Let’s take an example,

Suppose int aiData[3][3] is a 2D array that has 3 rows and 3 columns.  If you need to access the 2nd element of 1 row in aiData, then calculates its offset that will be ( 1 * coloumb_number) + 2 ) .  Now to access the element just add the offset in array base address and dereference it.

assign pointer to 2d array in c

Note: Array index always starts with 0, so 2nd means third element.

See the below steps for the above description,

Note: General expression to calculates offset for 2D array is that, (ithRow * Total_number_Coloumb)+ jthColoumb).

We know that the array element is stored in the contiguous form so we can also access the elements of the two-dimensional array to calculate the total number of cells.

See the below program,

If you want to learn more about the c language, here 10 Free days (up to 200 minutes)  C video course  for you.

C tutorial

Access 2d array using a pointer to an array

We can easily access a 2D array with the help of a pointer to the array. First, we need to define a new type for the 2d array using the typedef that helps you to avoid the complex syntax. If you don’t know typedef see this article, application of typedef. After the creation of a new type for the 2d array, create a pointer to the 2d array and assign the address of the 2d array to the pointer.

Similar to the two-dimensional array we can access three, fourth, … etc dimensional array using the pointers.

Recommended Articles for you:

  • Why is it faster to process sorted array than an unsorted array?
  • How to create dynamic array in C?
  • How to pass an array as a parameter in C?
  • A brief description of the pointer in C .
  • Introduction of Array in C .
  • Dangling, Void, Null and Wild Pointers
  • Function pointer in c, a detailed guide
  • How to use the structure of function pointer in c language?
  • Function pointer in structure.
  • Pointer Arithmetic in C.
  • void pointer in C.
  • 10 questions about dynamic memory allocation.
  • Memory Layout in C.
  • 100 C interview Questions
  • Implement state machine in C.
  • What is flexible array member in c?
  • What is importance of struct hack in c?
  • Create a students management system in C.
  • Create an employee management system in C.
  • Top 11 Structure Padding Interview Questions in C
  • File handling in C.
  • C format specifiers.

You might also like

embedded c interview questions

Embedded C interview questions and answers (2024)

C program to calculate simple interest, c program to convert fahrenheit to celsius.

Difference between ++*p, *p++ and *++p

Difference between ++*p, *p++ and *++p

31 comments.

#include #include void main() { int a[2][2],i,j,*p; printf(“enter the value of rows and column\n”); for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { scanf("%d",&a[i][j]); } } printf("\n"); p=&a[0][0]; for(i=0;i<=1;i++) { for(j=0;j<=1;j++) {

printf("%d ",*(p+i*2+j)); //if it is 3*3 matrix then we use *(p+1*3+j) and so on; } printf("\n"); } getche();

  • Pingback: Replacing nested switches with the multi-dimensional array - AticleWorld
  • Pingback: Fibonacci Series Program In C: A simple introduction - AticleWorld
  • Pingback: C program to check valid date (date is valid or not) - AticleWorld
  • Pingback: A brief description of increment and decrement operators in c. - AticleWorld
  • Pingback: How to use the structure of function pointer in c language - AticleWorld
  • Pingback: How to create and use DLL (Dynamic Link Library) in (C++) - AticleWorld
  • Pingback: How to implement finite state machine in C - AticleWorld
  • Pingback: How to find sizeof array in C/C++ without using sizeof? - AticleWorld
  • Pingback: Program to check leap year in c language. - AticleWorld
  • Pingback: Find prime numbers up to n using trial division and Sieve of Eratosthenes algorithm - AticleWorld
  • Pingback: Format specifiers in C Programming language - AticleWorld
  • Pingback: How to find whether a given number is prime number or not in c ? - AticleWorld
  • Pingback: Pointer to string array in C - AticleWorld
  • Pingback: Find the smallest and second smallest element in an array - AticleWorld
  • Pingback: Difference between dangling pointer and memory leak - AticleWorld
  • Pingback: Dynamic memory allocation in C, a brief introduction - AticleWorld
  • Pingback: switch case in C/C++, A Brief Explanation - AticleWorld
  • Pingback: C Program to find the maximum and minimum element in the array - AticleWorld
  • Pingback: Write C program to find sum of array elements - AticleWorld
  • Pingback: C program to find sum of array elements using recursion - AticleWorld
  • Pingback: C program to segregate even and odd numbers - AticleWorld
  • Pingback: C Program to reverse the elements of an array - AticleWorld
  • Pingback: C program to find even occurring elements in an array of limited range - AticleWorld
  • Pingback: C program to find the most popular element in an array - AticleWorld
  • Pingback: Array interview questions in C/C++ with Answers - AticleWorld
  • Pingback: C program to find median of two sorted arrays of same size - AticleWorld
  • Pingback: C program to find median of two sorted arrays of different sizes - AticleWorld
  • Pingback: C program to move all negative numbers to beginning and positive to end with constant extra space - AticleWorld
  • Pingback: C Program to find the product of digits of a number - AticleWorld
  • Pingback: How to pass an array as a parameter in C? - Aticleworld

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Dynamically allocate memory for a 2D array in C

This post will discuss various methods to dynamically allocate memory for 2D array in C using Single Pointer , Array of Pointers , and Double Pointer .

1. Using Single Pointer

In this approach, we simply allocate memory of size M × N dynamically and assign it to the pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 2D array.

Download    Run Code

2. Using Array of Pointers

We can dynamically create an array of pointers of size M and then dynamically allocate memory of size N for each row, as shown below:

Dynamically allocate memory for 2D Array

3. Using Double Pointer

We start by creating an array of pointers of size M as seen in the 2nd method. Then dynamically allocate memory of size M × N and let *A point to it. Finally, position allocated memory across M pointers.

That’s all about dynamically allocating memory for a 2D array in C.

  Also See:

Dynamically allocate memory for a 3D array in C

Rate this post

Average rating 4.11 /5. Vote count: 9

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

assign pointer to 2d array in c

Software Engineer | Content Writer | 12+ years experience

guest

  • C Programming
  • Java Programming
  • Data Structures
  • Web Development
  • Tech Interview

One and Two-Dimensional Arrays and Pointers in C

One dimensional arrays in c, why array index in c starts from zero, two-dimensional arrays in c, passing two-dimensional array to a function in c, double pointer and two dimensional arrays in c, arrays in c programming.

Arrays in C or in any other programming language are container types that contain a finite number of homogeneous elements. Elements of an array are stored sequentially in memory and are accessed by their indices. Arrays in C language are static type and thence the size of array cannot be altered at runtime, but modern languages like Java, implement arrays as objects and give programmers facility to resize them at runtime. Arrays become useful storage containers when the size of the list is know beforehand.

Array name in C language behaves like a constant pointer and represents the base address of the array. It points to the first element of the array which is located at 0 th index. As array name serves like a constant pointer, it cannot be changed during the course of program execution. To demonstrate how arrays in C are defined, and accessed by the item index? How they are accessed by the help of pointers? Let's go through the following program and the description.

Array arr defined in above program contains 5 integer values stored at indices from 0 to 4. Array index starts from zero that's why index of the last element will be size of array minus one, that is, arr[4] in this case. Below is the pictorial representation of arr , where the array arr points to first element at location 0. This element has address 1024 that is the base address of the array and represented by the array name.

Pictorial representation of array arr

One Dimensional Arrays in C, Storage Demonstration

Elements stored in an array are accessed by following the syntax "arrayName[index]" e.g., arr[3] yields 4 in above example. This strategy computes the base address of the desired element by combining the base address of the array with the index of desired element. Every array element takes a fixed number of bytes, which is known at compile time and this is decided by the type of array. In above example array is of type integer thus consumes 4 bytes (size of integer) per element. So the address of any n th element in the array using 0 based indexing will be at an offset of (n * element_size) bytes from the base address of the array. You can devise the following formula to compute n th element address. n th element address = base address of array + (n * size of element in bytes)

The square bracket ([]) syntax to access array elements deals with address computation at its own. It takes the index that you wish to access, multiplies it with the element size, adds this resulting offset to the base address of the array, and finally dereferences the resulting pointer to get the desired element.

Now that you understand the computation of offset and then address of the element you want to access. Any element in the valid range of array can also be accessed by adding the index of that element to the base address and it computes the same offset as it was computed by square bracket syntax. But it leaves the result as a pointer and you have to dereference it at your own.

It should be clear from above passage of text that (arr + 3) is a pointer to the integer arr[3] , (arr + 3) is of type int* while arr[3] is of type int . The two expressions only differ by whether the pointer is dereferenced or not. Thus the expression (arr + 3) is exactly equivalent to the expression &arr[3] . In fact those two probably compile to exactly the same code. They both represent a pointer to the element at index 3. Any square bracket ([]) syntax expression can be written with the + syntax instead. We just need to add in the pointer dereference. Conclusively, arr[3] is exactly equivalent to *(arr + 3) .

Pay attention to the following lines to understand correct syntax of dereferencing. You can also write *(arr + 3) to *(3 + arr) , this is perfectly right and acceptable as addition is commutative. Likewise, can you write arr[3] to 3[arr] ? Yes, you can. But on the contrary [arr]3 or [3]arr is not correct and will result into syntax error, as (arr + 3)* and (3 + arr)* are not valid expressions. The reason is dereference operator should be placed before the address yielded by the expression not after the address.

The short answer is, it depends on language design whether the start index should be zero or any other positive integer of your choice. in Fortran, when an array is declared with integer a(10) (an array of 10 integer elements), the index starts from 1 and ends at 10. However, this behavior can be overridden using a statement like, integer a(0:9) , declaring an array with indices from 0 to 9. But In C language we do not have the freedom to start the array index from any other number than zero, and language strictly sticks to zero as start index of array. It is because in C the name of an array is a pointer, which is a reference to a memory location. Therefore, an expression *(arr + n) or arr[n] locates an element n-locations away from the starting location because the index is used as an offset. Likewise, the first element of the array is exactly contained by the memory location that array refers (0 elements away), so it should be denoted as *(arr + 0) or *(arr) or arr[0] . C programming language has been designed this way, so indexing from 0 is inherent to the language.

A two dimensional array (will be written 2-D hereafter) can be imagined as a matrix or table of rows and columns or as an array of one dimensional arrays. Following is a small program twoDimArrayDemo.c that declares a 2-D array of 4x3 ( 4 rows and 3 columns) and prints its elements.

The array elements in above program are stored in memory row after row sequentially; assuming array is stored in row major order. As you know array name behaves like a constant pointer and points to the very first element of the array. The same is true for 2-D arrays, array name matrix serves as a constant pointer, and points to the first element of the first row. Array elements within valid range of matrix can be accessed by following different syntaxes.

matrix[0][0] = *(*(matrix)) matrix[i][j] = *((*(matrix)) + (i * COLS + j)) matrix[i][j] = *(*(matrix + i) + j) matrix[i][j] = *(matrix[i] + j) matrix[i][j] = (*(matrix + i))[j] &matrix[i][j] = ((*(matrix)) + (i * COLS + j))

Passing 2-D array to a function seems tricky when you think it to pass as a pointer because a pointer to an array and pointer to a pointer (double pointer) are two different things. If you are passing a two dimensional array to a function, you should either use square bracket syntax or pointer to an array syntax but not double pointer. Why should not you use double pointer to access array elements will be described in next section. Let's rewrite twoDimArrayDemo.c as twoDimArrayDemoPtrVer.c and demonstrate passing 2-D array to function for printing array.

In twoDimArrayDemoPtrVer.c you see two ways of passing 2-D array to a function. In first function array_of_arrays_ver array of arrays approach is used, while is second function ptr_to_array_ver pointer to array approach is used.

Another very important point to note is the called function does not allocate space for the array and it does not need to know the overall size, so the number of rows can be omitted. Space is not allocated because called function does not create a local copy of the array rather it uses the original one that has been passed to it. The width of the array is still important because number of elements contained by one row has to be told to compiler in order to increment the pointer to point the next row. So the column dimension COLS must be specified.

While trying to access a 2-D array by a double pointer compiler may not prevent you from doing so but you would not get expected results in some situations. Let's have a look at the following program twoDimArrayDblPtrVer.c and its generated output.

It happens because two dimensional array matrix and double pointer pmat are different types and using them in similar fashion points to different locations in memory. The following piece of code aborts the program with a "memory access violation" error.

And, you might have guessed why this access violation error is? Because the same memory location is being dereferenced two times, that's why this access violation error. To conclude, arrays in C are containers for homogeneous elements. Array elements can be accessed and modified with help of the pointers.

In this tutorial we talked of one dimensional arrays in C, why array index in C starts from zero, two dimensional arrays, passing 2-D array to a function, and double pointer and two dimensional arrays. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

  • Essential C
  • Arrays and Pointers in C
  • C Programming Tutorials
  • Java Programming Tutorials
  • Data Structures Tutorials
  • All Tech Interview Questions
  • C Interview Question Answers
  • Java Interview Question Answers
  • DSA Interview Question Answers

Get Free Tutorials by Email

About the Author

Author Photo

Krishan Kumar is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

  • Write For Us

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
  • Calculate Average Using Arrays
  • Find Largest Element in an Array

C Multidimensional Arrays

  • Access Array Elements Using Pointer

Relationship Between Arrays and Pointers

  • Store Information of Students Using Structure

C arrays

An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it.

How to declare an array?

For example,

Here, we declared an array, mark , of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0] , the second element is mark[1] and so on.

C Array declaration

Few keynotes :

  • Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
  • If the size of an array is n , to access the last element, the n-1 index is used. In this example, mark[4]
  • Suppose the starting address of mark[0] is 2120d . Then, the address of the mark[1] will be 2124d . Similarly, the address of mark[2] will be 2128d and so on. This is because the size of a float is 4 bytes.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

You can also initialize an array like this.

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Initialize an array in C programming

Change Value of Array elements

Input and output array elements.

Here's how you can take input from the user and store it in an array element.

Here's how you can print an individual element of an array.

Example 1: Array Input/Output

Here, we have used a  for loop to take 5 inputs from the user and store them in an array. Then, using another  for loop, these elements are displayed on the screen.

Example 2: Calculate Average

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

You can access the array elements from testArray[0] to testArray[9] .

Now let's say if you try to access testArray[12] . The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.

Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays

In this tutorial, you learned about arrays. These arrays are called one-dimensional arrays.

In the next tutorial, you will learn about multidimensional arrays (array of an array) .

Table of Contents

  • C Arrays (Introduction)
  • Declaring an Array
  • Access array elements
  • Initializing an array
  • Change Value of Array Elements
  • Array Input/Output
  • Example: Calculate Average
  • Array Elements Out of its Bound

Video: C Arrays

Sorry about that.

Related Tutorials

Pass arrays to a function in C

C Dynamic Memory Allocation

  • 90% Refund @Courses
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Related Articles

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

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

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

What is a Pointer in C?

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

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

Syntax of C Pointers

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

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

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

How to Use Pointers?

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

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

1. Pointer Declaration

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

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

2. Pointer Initialization

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

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

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

3. Pointer Dereferencing

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

dereferencing a pointer in c

Dereferencing a Pointer in C

C Pointer Example

Types of pointers in c.

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

1. Integer Pointers

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

These pointers are pronounced as Pointer to Integer.

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

2. Array Pointer

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

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

3. Structure Pointer

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

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

4. Function Pointers

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

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

5. Double Pointers

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

Dereferencing Double Pointer

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

6. NULL Pointer

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

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

7. Void Pointer

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

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

8. Wild Pointers

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

9. Constant Pointers

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

10. Pointer to Constant

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

Other Types of Pointers in C:

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

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

Size of Pointers in C

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

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

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

How to find the size of pointers in C?

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

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

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

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

C Pointer Arithmetic

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

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

C Pointers and Arrays

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

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

Example 1: Accessing Array Elements using Pointer with Array Subscript

relationship between array and pointer

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

Example 2: Accessing Array Elements using Pointer Arithmetic

accessing array elements using pointer arithmetic

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

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

Uses of Pointers in C

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

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

Advantages of Pointers

Following are the major advantages of pointers in C:

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

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:

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

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

FAQs on Pointers in C

Q1. define pointers..

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

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

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

Q3. What is pointer to pointer?

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

Q4. Does pointer size depends on its type?

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

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

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

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

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

Please Login to comment...

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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. C

    assign pointer to 2d array in c

  2. Array using Pointer

    assign pointer to 2d array in c

  3. C Programming Tutorial

    assign pointer to 2d array in c

  4. How to access two dimensional array using pointers in C

    assign pointer to 2d array in c

  5. C++ return 2d array from function

    assign pointer to 2d array in c

  6. Using Pointers to Print 2D Arrays

    assign pointer to 2d array in c

VIDEO

  1. Pointer in Array || C Programming

  2. C++ Array and Pointer Exercises

  3. #22 2D Array and Pointer

  4. #21 Pointer to an Array & Array of Pointers

  5. Java Programming , use a 2 D array to assign prices to seats

  6. Lecture 90||2D array with pointers||C programming Tutorials||Complete Playlist||Placements||

COMMENTS

  1. Pointer to 2D arrays in C

    To achieve this, we can do : int (*pointer) [280]; // pointer creation pointer = tab1; //assignation pointer [5] [12] = 517; // use int myint = pointer [5] [12]; // use or, alternatively : int (*pointer) [100] [280]; // pointer creation pointer = &tab1; //assignation (*pointer) [5] [12] = 517; // use int myint = (*pointer) [5] [12]; // use

  2. How to declare a Two Dimensional Array of pointers in C?

    How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr [5] [5]; //creating a 2D integer pointer array of 5 rows and 5 columns. The element of the 2D array is been initialized by assigning the address of some other element.

  3. Pointers and 2-D arrays

    How it works: Here p is a pointer which points to the 0th element of the array my_arr, while parr is a pointer which points to the whole array my_arr. The base type of p is of type ( int *) or pointer to int and base type of parr is pointer to an array of 5 integers.

  4. How to access two dimensional array using pointers in C programming

    Since array decays to pointer. * (matrix) => Points to first row of two-dimensional array. * (matrix + 0) => Points to first row of two-dimensional array. * (matrix + 1) => Points to second row of two-dimensional array. **matrix => Points to matrix [0] [0] * (* (matrix + 0)) => Points to matrix [0] [0] * (* (matrix + 0) + 0) => Points to matri...

  5. C

    We will assign the address of the first element of the array num to the pointer ptr using the address of & operator. int *ptr = &num [0] [0]; Accessing the elements of the two dimensional array via pointer The two dimensional array num will be saved as a continuous block in the memory.

  6. C Programming/Pointers and arrays

    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.

  7. C Multidimensional Arrays (2d and 3d Array)

    C Multidimensional Arrays. In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns. Similarly, you can declare a three-dimensional (3d) array.

  8. How to access two dimensional array using pointers in C

    First, we need to define a new type for the 2d array using the typedef that helps you to avoid the complex syntax. If you don't know typedef see this article, application of typedef. After the creation of a new type for the 2d array, create a pointer to the 2d array and assign the address of the 2d array to the pointer.

  9. A Pointer to a Pointer in C: Foundation for Multidimensional Arrays

    A Pointer to a Pointer in C: Foundation for Multidimensional Arrays. Dolamu Oludare · Follow Published in Dev Genius · 8 min read · Oct 31, 2023 Photo by Luis Gonzalez on Unsplash It is burdensome to realize that even while struggling to understand what pointers are, there is still something called a pointer to a pointer.

  10. Multidimensional Arrays in C

    A two-dimensional array or 2D array in C is the simplest form of the multidimensional array. We can visualize a two-dimensional array as an array of one-dimensional arrays arranged one over another forming a table with 'x' rows and 'y' columns where the row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).

  11. How to allocate a 2D array of pointers in C++

    // Create 2D array of pointers: int*** array2d = new (int**) [rows]; for (int i = 0; i < rows; ++i) { array2d [i] = new (int*) [cols]; } // Null out the pointers contained in the array: for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array2d [i] [j] = NULL; } }

  12. Pointer to an Array

    Syntax: data_type (*var_name) [size_of_array]; Here: data_type is the type of data that the array holds. var_name is the name of the pointer variable. size_of_array is the size of the array to which the pointer will point. Example int (*ptr) [10]; Here ptr is pointer that can point to an array of 10 integers.

  13. Dynamically allocate memory for a 2D array in C

    1. Using Single Pointer. In this approach, we simply allocate memory of size M × N dynamically and assign it to the pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 2D array. 2. Using Array of Pointers. We can dynamically create an array of pointers of size M and then dynamically allocate memory ...

  14. One, Two-Dimensional (2D) Arrays and Pointers in C

    Two-Dimensional Arrays in C. A two dimensional array (will be written 2-D hereafter) can be imagined as a matrix or table of rows and columns or as an array of one dimensional arrays. Following is a small program twoDimArrayDemo.c that declares a 2-D array of 4x3 ( 4 rows and 3 columns) and prints its elements.

  15. Two dimensional (2D) arrays in C programming with example

    An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also known as matrix. A matrix can be represented as a table of rows and columns. Let's take a look at the following C program, before we discuss more about two Dimensional array. Simple Two dimensional(2D) Array Example

  16. C assigning the address of a 2D array to a pointer

    C assigning the address of a 2D array to a pointer Ask Question Asked 9 years, 11 months ago Modified 9 years, 11 months ago Viewed 2k times 3 I was reading through some lecture notes that in order for a pointer to reference a 2D array, it has to be given the address of the first element. int a [10] [10]; int *p = &a [0] [0];

  17. Array of Pointers in C

    It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it. Syntax: pointer_type *array_name [array_size]; Here, pointer_type: Type of data the pointer is pointing to. array_name: Name of the array of pointers.

  18. C Arrays (With Examples)

    How to declare an array? dataType arrayName [arraySize]; For example, float mark [5]; Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values. It's important to note that the size and type of an array cannot be changed once it is declared. Access Array Elements

  19. Assigning value to two dimensional array with the use of pointers C++

    Assigning value to two dimensional array with the use of pointers C++ Ask Question Asked 5 years, 9 months ago Modified 5 years, 9 months ago Viewed 2k times 0 I have a task which states: "your task is to fill the 10x10 matrix with values that will turn it into a multiplication table. You mustn't use brackets. You mustn't use indexing.

  20. C Pointers

    Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) ... C Pointers and Arrays. In C programming language, pointers and arrays are closely related. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element.

  21. assignment of arrays to pointers in C

    but can we directly assign a double pointer as: t->text = { "IF WE COULD TAKE THE TIME", "TO LAY IT ON THE LINE", "I COULD REST MY HEAD" }; Also why does this work: char *arr [3] = { "IF WE COULD TAKE THE TIME", "TO LAY IT ON THE LINE", "I COULD REST MY HEAD" }; t->text = arr; c Share Improve this question Follow edited Dec 28, 2018 at 8:37

  22. c++

    Basically, The child class contains a member as a pointer to an array of pointers to Toy objects. Now, While writing the move assign constructor , should i redirect the pointer the array members in a loop first and then delete the source object or just point the array pointer to the new Toy Child object without going through individual members?

  23. Sorting an Array of Pointers in C++

    I think what's happening is that the values that arrptr[] are pointing to are being sorted and in turn the data[] array is somehow being messed up. I tried using a pointer to a pointer but only got errors (int** to int* conversion). For reference this is how I assigned the pointer array to the data array.