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

What is the difference between ++var and var++?
First one is present increment and second one is the post incremental t of the variable. Both increases value of var to one. The difference between pre and post increment is given in below example. Int...
Chittaranjan
If one leaves a lot of space in a C language code, will it require more space in a hard disk and RAM?
Head files tells system, how to deal with different functions with program such as printf(), scanf() , getche() etc. so you must have reference to it.
Abhishek
0 0
5
What is a macro, and how do you use it?
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look...
Sandeep
Can we pass arguments in the main function in C language?
Yes. it is possible to pass arguments into the main function.
Mukesh
0 0
7
Why is a compiler used for language C and not an interpreter?
C is a structured programming language. It’s code consists of many macros, function calls references etc., which is required to be decoded before program’s execution can take place, so that any error is...
Savitha
0 0
5

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 FOR GENERATING SOUND
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { sound(3000); // sound function have single parameter , this parameter we put integer value its generating...

V. Muthu Ganeshan

0 0
0

Internet of Things, Social Media Becoming Part of E-Discovery Landscape
The days when e-discovery consisted of handing over copies of e-mails to address Freedom of Information Act (FOIA) requests, compliance regulations or other legal obligations are over. Now, it's just as...

Find out the Output of the following with reason and get C Language Training fess less by 10%
1. void main() { clrscr(); printf(5+"Beautifull"); getch(); } 2. void main() { int a=50; clrscr(); ...

Understanding Computer Science Concepts with Images and Videos..
All Computer science concepts relating to programming and software development are only virtual. It cannot be practically shown as a hardware parts of a computer. But for better understanding it should...

Program to swap the value of two variables without using third variable(simplest way)...
int main() { int a=10,b=20; printf("values of a before swap ="%d,a); printf("values of b before swap ="%d,b); a=a+b; b=a-b; a=a-b; printf("******************"); printf("values of a after swap...

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