The Wayback Machine - https://web.archive.org/web/20240917160543/https://www.geeksforgeeks.org/multidimensional-pointer-arithmetic-in-cc/
Open In App

Multidimensional Pointer Arithmetic in C/C++

Last Updated : 28 Sep, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C/C++, arrays and pointers have similar semantics, except on type information.

As an example, given a 3D array

int buffer[5][7][6];

An element at location [2][1][2] can be accessed as “buffer[2][1][2]” or *( *( *(buffer + 2) + 1) + 2).

Observe the following declaration

T *p; // p is a pointer to an object of type T

When a pointer p is pointing to an object of type T, the expression *p is of type T. For example buffer is of type array of 5 two dimensional arrays. The type of the expression *buffer is “array of arrays (i.e. two dimensional array)”.

Based on the above concept translating the expression *( *( *(buffer + 2) + 1) + 2) step-by-step makes it more clear.

  1. buffer – An array of 5 two dimensional arrays, i.e. its type is “array of 5 two dimensional arrays”.
  2. buffer + 2 – displacement for 3rd element in the array of 5 two dimensional arrays.
  3. *(buffer + 2) – dereferencing, i.e. its type is now two dimensional array.
  4. *(buffer + 2) + 1 – displacement to access 2nd element in the array of 7 one dimensional arrays.
  5. *( *(buffer + 2) + 1) – dereferencing (accessing), now the type of expression “*( *(buffer + 2) + 1)” is an array of integers.
  6. *( *(buffer + 2) + 1) + 2 – displacement to get element at 3rd position in the single dimension array of integers.
  7. *( *( *(buffer + 2) + 1) + 2) – accessing the element at 3rd position (the overall expression type is int now).

The compiler calculates an “offset” to access array element. The “offset” is calculated based on dimensions of the array. In the above case, offset = 2 * (7 * 6) + 1 * (6) + 2. Those in blue colour are dimensions, note that the higher dimension is not used in offset calculation. During compile time the compiler is aware of dimensions of array. Using offset we can access the element as shown below,

element_data = *( (int *)buffer + offset );

It is not always possible to declare dimensions of array at compile time. Sometimes we need to interpret a buffer as multidimensional array object. For instance, when we are processing 3D image whose dimensions are determined at run-time, usual array subscript rules can’t be used. It is due to lack of fixed dimensions during compile time. Consider the following example,

int *base;

Where base is pointing large image buffer that represents 3D image of dimension l x b x h where l, b and h are variables. If we want to access an element at location (2, 3, 4) we need to calculate offset of the element as

offset = 2 * (b x h) + 3 * (h) + 4 and the element located at base + offset.

Generalizing further, given start address (say base) of an array of size [l x b x h] dimensions, we can access the element at an arbitrary location (a, b, c) in the following way,

data = *(base + a * (b x h) + b * (h) + c); // Note that we haven’t used the higher dimension l.

The same concept can be applied to any number of dimensions. We don’t need the higher dimension to calculate offset of any element in the multidimensional array. It is the reason behind omitting the higher dimension when we pass multidimensional arrays to functions. The higher dimension is needed only when the programmer iterating over limited number of elements of higher dimension.

A C/C++ puzzle, predict the output of following program




int main()
{
    char arr[5][7][6];
    char (*p)[5][7][6] = &arr;
  
    /* Hint: &arr; - is of type const pointer to an array of
       5 two dimensional arrays of size [7][6] */
  
    printf("%d\n", (&arr; + 1) - &arr;);
    printf("%d\n", (char *)(&arr; + 1) - (char *)&arr;);
    printf("%d\n", (unsigned)(arr + 1) - (unsigned)arr);
    printf("%d\n", (unsigned)(p + 1) - (unsigned)p);
  
    return 0;
}


Output:

1

210

42

210

Thanks to student for pointing an error.

— Venki.



Similar Reads

C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = & normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
C - Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha
5 min read
Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
C++ Pointer Arithmetic
In C++, pointer variables are used to store the addresses of other variables, functions, structures, and even other pointers and we can use these pointers to access and manipulate the data stored at that address. Pointer arithmetic means performing arithmetic operations on pointers. It refers to the operations that are valid to perform on pointers.
8 min read
How to print dimensions of multidimensional array in C++
Create a function that prints multidimensional array size by dimensions i.e.:Examples: Input : int a[2][3][4]; printDimensions(a); Output : 2x3x4 Input : int b[5][6]; printDimensions(a); Output : 5x6 To solve this problem we should use template function to figure out the size of current array. Then we call this function recursively till the last di
2 min read
C++ Multidimensional Array
An array is a type of data structure used to store the collection of the same data type items held at contiguous memory locations. Arrays can be one-dimensional or multidimensional based on the number of directions in which the array can grow. In this article, we will study multidimensional arrays such as two-dimensional arrays and three-dimensiona
9 min read
How to Get Value of Multidimensional Array in C?
Prerequisite: Array in C An array is a type of data structure where we can store multiple elements of similar data types. A multidimensional array can be termed an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. Declaration of Array Declaration or Initialisation of an arra
8 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
Initialization of Multidimensional Array in C
In C, initialization of a multidimensional array can have left most dimensions as optional. Except for the leftmost dimension, all other dimensions must be specified. For example, the following program fails in compilation because two dimensions are not specified. C/C++ Code #include <stdio.h> int main() { int a[][][2] = { { { 1, 2 }, { 3, 4
2 min read
Initialization of Multidimensional Arrays in C++
In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++. Methods to Initialize Multidimensional Array in C++We can initialize multidimensional arrays in C++ using the following ways: Initi
3 min read
Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multidimensional arrays in C programming language. Synta
10 min read
How to declare a pointer to a function?
While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple... int *ptrInteger; /*We have put a * operator between int and ptrInt
2 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
NULL Pointer in C
The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard: “An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guarantee
4 min read
C | Pointer Basics | Question 1
What is the output of following program? # include <stdio.h> void fun(int x) { x = 30; } int main() { int y = 20; fun(y); printf("%d", y); return 0; } (A) 30 (B) 20 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: Parameters are always passed by value in C. Therefore, in the above code, value of y is not modified using
1 min read
C | Pointer Basics | Question 2
Output of following program? # include <stdio.h> void fun(int *ptr) { *ptr = 30; } int main() { int y = 20; fun(&y); printf("%d", y); return 0; } (A) 20 (B) 30 (C) Compiler Error (D) Runtime Error Answer: (B) Explanation: The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value
1 min read
C | Pointer Basics | Question 3
Output of following program? #include <stdio.h> int main() { int *ptr; int x; ptr = &x; *ptr = 0; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); *ptr += 5; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr); (*ptr)++; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr);
2 min read
C | Pointer Basics | Question 4
Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes. #include <stdio.h> int main() { int arri[] = {1, 2 ,3}; int *ptri = arri; char arrc[] = {1, 2 ,3}; char *ptrc = arrc; printf("sizeof arri[] = %d ", sizeof(arri)); printf("sizeof ptri = %d ", sizeof(ptri)); printf("sizeof arrc[] =
1 min read
C | Pointer Basics | Question 17
Assume that float takes 4 bytes, predict the output of following program. #include <stdio.h> int main() { float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; float *ptr1 = &arr[0]; float *ptr2 = ptr1 + 3; printf("%f ", *ptr2); printf("%d", ptr2 - ptr1); return 0; } (A) 90.500000 3 (B) 90.500000 12 (C) 10.000000 12 (D) 0.5000
1 min read
C | Pointer Basics | Question 6
#include<stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; } Assume that an int variable takes 4 bytes and a
2 min read
C | Pointer Basics | Question 7
#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } What is the output of above program? (A) Machine dependent (B) 513 (C) 258 (D) Compiler Error Answer: (A) Explanation: Output is 513 in a little endian machine. To understand this output, let integers be sto
1 min read
C | Pointer Basics | Question 8
C/C++ Code int main() { char *ptr = \"GeeksQuiz\"; printf(\"%c", *&*&*ptr); return 0; } (A) Compiler Error (B) Garbage Value (C) Runtime Error (D) G Answer: (D)Explanation: The operator * is used for dereferencing and the operator & is used to get the address. These operators cancel out effect of each other when used one after another. We can a
1 min read
C | Advanced Pointer | Question 1
C/C++ Code void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); return 0; } (A) 10 (B) 20 (C) Compiler error (D) Runtime Error Answer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local poi
2 min read
C | Advanced Pointer | Question 2
Assume sizeof an integer and a pointer is 4 byte. Output? #include <stdio.h> #define R 10 #define C 20 int main() { int (*p)[R][C]; printf("%d", sizeof(*p)); getchar(); return 0; } (A) 200 (B) 4 (C) 800 (D) 80 Answer: (C) Explanation: Output is 10*20*sizeof(int) which is “800″ for compilers with integer size as 4 bytes. When a point
1 min read
C | Pointer Basics | Question 17
#include<stdio.h> void fun(int arr[]) { int i; int arr_size = sizeof(arr)/sizeof(arr[0]); for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); } int main() { int i; int arr[4] = {10, 20 ,30, 40}; fun(arr); return 0; } (A) 10 20 30 40 (B) Machine Dependent (C) 10 20 (D) Northing Answer: (B) Explanation: In C, array parameters are
2 min read
C | Pointer Basics | Question 10
The reason for using pointers in a C program is (A) Pointers allow different functions to share and modify their local variables. (B) To pass large structures so that complete copy of the structure can be avoided. (C) Pointers enable complex “linked\" data structures like linked lists and binary trees. (D) All of the above Answer: (D)Explanation: S
1 min read
C | Pointer Basics | Question 11
C/C++ Code #include void f(int *p, int *q) { p = q; *p = 2; } int i = 0, j = 1; int main() { f(&i, &j); printf(\"%d %d", i, j); getchar(); return 0; } (A) 2 2 (B) 2 1 (C) 0 1 (D) 0 2 Answer: (D)Explanation: See below f() with comments for explanation. /* p points to i and q points to j */ void f(int *p, int *q) { p = q; /* p also points to j now */
1 min read
Article Tags :
Practice Tags :