UrbanPro

Learn C Language from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

How do I access two dimensional array with the help of the pointers?

Asked by Last Modified  

Follow 2
Answer

Please enter your answer

Advance Excel And VBA Training

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...
read more
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. /* Program: twoDimArrayDemo.c */ #include "stdio.h" #define ROWS 4 #define COLS 3 int main () { // declare 4x3 array int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } return 0; } 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 Two-Dimensional Array to a Function in C 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. /* Program: twoDimArrayDemoPtrVer.c */ #include "stdio.h" #define ROWS 4 #define COLS 3 void array_of_arrays_ver(int arr[][COLS]); /* prototype */ void ptr_to_array_ver(int (*arr)[COLS]); /* prototype */ int main () { // declare 4x3 array int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; printf("Printing Array Elements by Array of Arrays Version Function: \n"); array_of_arrays_ver(matrix); printf("Printing Array Elements by Pointer to Array Version Function: \n"); ptr_to_array_ver(matrix); return 0; } void array_of_arrays_ver(int arr[][COLS]) { int i, j; for (i = 0; i < ROWS; i++) { for (j = 0; j < COLS; j++) { printf("%d\t", arr[i][j]); } printf("\n"); } } void ptr_to_array_ver(int (*arr)[COLS]) { int i, j; for (i = 0; i < ROWS; i++) { for (j = 0; j < COLS; j++) { printf("%d\t", (*arr)[j]); } arr++; printf("\n"); } } OUTPUT ====== Printing Array Elements by Array of Arrays Version Function: 1 2 3 4 5 6 7 8 9 10 11 12 Printing Array Elements by Pointer to Array Version Function: 1 2 3 4 5 6 7 8 9 10 11 12 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. Double Pointer and Two Dimensional Arrays in C 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. /* Program: twoDimArrayDblPtrVer.c */ #define ROWS 4 #define COLS 3 int main () { // matrix of 4 rows and 3 columns int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; int** pmat = (int **)matrix; printf("&matrix[0][0] = %u\n", &matrix[0][0]); printf("&pmat[0][0] = %u\n", &pmat[0][0]); return 0; } OUTPUT ====== &matrix[0][0] = 124 &pmat[0][0] = 1 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. printf("pmat[0][0] = %u\n", pmat[0][0]); 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. read less
Comments

Tutor

you need to declare pointer to 1-D array like syntax is data_type (*ptr), or you can declare a pointe rto 2-D aray, here if your 2-D array is like say int arr2,it will consist if two one d array with 3 element of each array, you can declare a pointer as *pt=arr, it will store the base add of your first...
read more
you need to declare pointer to 1-D array like syntax is data_type (*ptr)[Size], or you can declare a pointe rto 2-D aray, here if your 2-D array is like say int arr[]2[3],it will consist if two one d array with 3 element of each array, you can declare a pointer as *pt=arr, it will store the base add of your first one d array, if you increment a pointer variable like pt++ it will point to 0th element of next one d array, so if you want to acess the individual elements of array the your can use *(*(arr+i)+j) where I referers to number of 1 d arays and j refe to number of elements in yur each one d array, so 0<=i<=1 and 0<=j<=2; e.g if you want to access the 2nd element of first one d array then you can use pt[0][1] and to get its value use *pt[0][1], still not understood then you are not clear with arays and its subscripts with pointer, so you need to read any standard book for C and clear your basics of arrays.. read less
Comments

Sr. Software Engineer at Bureau Veritas, former Sr. Software Consultant at Aptech Malviynagar

you can simply try as you have done for 1D array. For 1D Array you might have done like - int arr={1,2,3,4,5}; int *p=arr; //for accessing array element through pointer printf("%d",*p);//1 printf("\n %d",*(p+1));//2 in the same way you can get the output by using 2D array int arr={{1,2,3},{4,5,6}}; int...
read more
you can simply try as you have done for 1D array. For 1D Array you might have done like - int arr[5]={1,2,3,4,5}; int *p=arr; //for accessing array element through pointer printf("%d",*p);//1 printf("\n %d",*(p+1));//2 in the same way you can get the output by using 2D array int arr[2][3]={{1,2,3},{4,5,6}}; int *p=arr;//gives compilation error since this time arr return the pointer of type 1D array int **p=arr; printf("%d",*(arr+1));//return address of arr[1][0] printf("%d",*(*(arr+1))+2; //return element of arr[1][2]//6 hope this will answer your question. Good Luck!! read less
Comments

View 1 more Answers

Related Questions

Do every operator has an Associativity?
Yes, every operator will have an associativity.
Basundhara
0 0
5
How can I try to remember the coding in C language?
One shouldn't try to remember the coding. The right approach is to understand the logical solution to the problem.
Chinmayee
0 0
5
What are all the data types in C programming with their details?
In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations...
Ganga
0 0
6
In which program we use character constants?
For the name of months, animal, colors we do use it.
Mona
Can an array be an lvalue?
The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes. The following statement is therefore illegal:...
Vinodha

Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com

Ask a Question

Related Lessons


C Program-The Odd Loop Demo
/* WAP to print square value of the number entered by user using odd loop*/ //Header Files #include<stdio.h>#include<conio.h> //Main Function void main(){ char another='y'; int num,sq; //...
S

C Program-Infinite Loop[For] Demo
//Header Files #include<stdio.h>#include<conio.h> //Main function void main(){ //Function for clearing screen clrscr(); //Infinite for loop for(;;) { printf("Hello!"); } //Function for...
S

What is Safety-Critical Software?
A software whose failure may cause death or injuries to the users called Safety-Critical Software.The software present as part of Aeroplanes, or present in Rail as railway signalling software or Automotive...

INTRODUCTION TO PROGRAMMING LANGUAGES
Language is a medium for communication. If we want to perform anything with another person, we can know the human language as a human being. Similarly, if we want to perform anything with a computer, we...

Recommended Articles

Brilliant Academy is one of the reputed institutes for B.Tech tuition classes. This institute is specialised in delivering quality tuition classes for B.E, Engineering - all streams and Engineering diploma courses. Incorporated in 2012, Brillant Academy is a brainchild of Mr Jagadeesh. The main motto of the academy is to...

Read full article >

Lasya Infotech is a Hyderabad based IT training institute founded in 2016 by O Venkat. Believing in his innovation, passion and persistence and with a diverse blend of experience, he started his brainchild to deliver exemplary professional courses to aspiring candidates by honing their skills. Ever since the institute envisions...

Read full article >

Software Development has been one of the most popular career trends since years. The reason behind this is the fact that software are being used almost everywhere today.  In all of our lives, from the morning’s alarm clock to the coffee maker, car, mobile phone, computer, ATM and in almost everything we use in our daily...

Read full article >

Business Process outsourcing (BPO) services can be considered as a kind of outsourcing which involves subletting of specific functions associated with any business to a third party service provider. BPO is usually administered as a cost-saving procedure for functions which an organization needs but does not rely upon to...

Read full article >

Looking for C Language Classes?

Learn from the Best Tutors on UrbanPro

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you
X

Looking for C Language Classes?

The best tutors for C Language Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn C Language with the Best Tutors

The best Tutors for C Language Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more