Find the best tutors and institutes for C Language

Find Best C Language Classes

Please select a Category.

Please select a Locality.

No matching category found.

No matching Locality found.

Outside India?

Search for topics

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

Asked by Last Modified  

IT Courses/Programming Languages/C Language

Follow 2
Answer

3 Answers

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 Trainer

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

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

Ask a Question

Related Lessons

Some Tricky Questions in C
Can you write two functions in which one executes before main function and other executes after the main function? #pragma startup #pragma exit Where, priority is optional integer value.For user priority...

Sahana D. | 16 Feb

0 0
0

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...

Rohan | 17/11/2018

2 0
1

Advantages of C++ Language
Advantages of C++ - C++ is a profoundly convenient dialect and is frequently the dialect of decision for multi-gadget, multi-stage application advancement. - C++ is a protest situated programming dialect...

Recommended Articles

Microsoft Excel is an electronic spreadsheet tool which is commonly used for financial and statistical data processing. It has been developed by Microsoft and forms a major component of the widely used Microsoft Office. From individual users to the top IT companies, Excel is used worldwide. Excel is one of the most important...

Read full article >

Applications engineering is a hot trend in the current IT market. An applications engineer is responsible for designing and application of technology products relating to various aspects of computing. To accomplish this, he/she has to work collaboratively with the company s manufacturing, marketing, sales, and customer...

Read full article >

Information technology consultancy or Information technology consulting is a specialized field in which one can set their focus on providing advisory services to business firms on finding ways to use innovations in information technology to further their business and meet the objectives of the business. Not only does...

Read full article >

Almost all of us, inside the pocket, bag or on the table have a mobile phone, out of which 90% of us have a smartphone. The technology is advancing rapidly. When it comes to mobile phones, people today want much more than just making phone calls and playing games on the go. People now want instant access to all their business...

Read full article >

Looking for C Language Classes?

Find best C Language Classes in your locality on UrbanPro.

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you

Find Best C Language Classes?

Find Now »

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 25 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 6.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