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

Asked by Last Modified  

Follow 2
Answer

Please enter your answer

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

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

View 1 more Answers

Related Questions

What is meant by high-order and low-order bytes?
Lower order and higher-order bytes are the terms used while computing calculations in a programming language. Usually, numbers are written from left to right. The left is the most significant bit, and...
Vishal
0 0
9
Why we use 'include stdio.h'?
The header file which is added to the program that one has written is basically what 'include stdio.h.' means. Stdio.h is known to contain the input and output operations like "printf" or "scanf" etc....
Jina
How can I develop my C language?
To develop your skills in the C programming language, consider the following steps: 1. Learn the Basics: Start with understanding the fundamental concepts of C, such as variables, data types, operators,...
Himanshu
0 0
5
What are the control statements in C language?
Control statements in C are constructs that allow the program to make decisions and control the flow of execution based on certain conditions. The primary control statements in C include if-else statements,...
Jitender
0 0
6
what is syntex error
A syntax error is an error which found in the source code of a program or sometimes it can be small grammatical mistakes in spelling or limited to a single character. Programming languages follow their...
Tanha

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

Ask a Question

Related Lessons

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


Static and dynamic libraries
A library is a package of code that is meant to be reused by many programs. A static library (also known as an archive) consists of routines that are compiled and linked directly into your program. When...

What Are IT Industries Performance Metrics?
1. Outstanding Expectation: Eligible to get Promotion easily and good salary hike. Always preferrable to go abroad. 2. Exceed Expectation: Can get Promotion as per schedule of company with good salary...

C Programming basics
C PROGRAMMING BASICS 10 Hours Introduction to ‘ C’ programming –fundamentals – structure of a ‘C’...
O

Om K.

0 0
0

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