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

Which book is best for learning C programming by a beginner?
C Programming Absolute Beginner's Guide Greg Perry, Dean Miller BeginnersLow-Level Programming: C, Assembly, and Program Execution Igor Zhirkov AdvancedC Programming in easy steps (5th Edition) Mike McGrath Beginners
Anil
0 0
8
How do I program a game using C program?
Programming a game in C involves several steps. Here's a simplified guide to get you started: Define Your Game Concept: Clearly outline the game's concept, rules, and objectives. Setup Your Development...
Sumitha
0 0
6
What is C? Where it is used ?
C has the advantage that it is a relatively small language, which makes it easy to implement a C compiler (whereas a C++ compiler is a monster to write), and makes it easier to learn the language. C...
Chandi
Is it better to bitshift a value than to multiply by 2?
yes in bitshifting operation, u know the shifting position of bit
Nadare
0 0
5
Which is the best C language IDE/compiler for Windows?
Let us now check out some of the famous and best-working IDEs available. Visual Studio Code. Visual Studio Code is one of the most popular IDEs and is open-source software developed by Microsoft....
Deepashri
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-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

Pointers and References
Are reference and pointers same? No. I have seen this confusion crumbling up among the student from the first day. So better clear out this confusion at thevery beginning. Pointers and reference...

Be prepared to get trained--init
Before starting the training,students must be mentally prepared for acceptance of new knowledge. Students must attend training with open minded forgetting the position they are working.This will help...
S

Smartnub Softsolutions

0 0
0


Necessity of Theory and Practical in Computer Science.
Upon studying a subject both theory and practical are important. Usually many schools concentrate more on theory and the marks not on the practical. Other and opposite kind of people prefer practical...

Recommended Articles

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 >

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 >

Hadoop is a framework which has been developed for organizing and analysing big chunks of data for a business. Suppose you have a file larger than your system’s storage capacity and you can’t store it. Hadoop helps in storing bigger files than what could be stored on one particular server. You can therefore store very,...

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 >

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