1

Can someone explain why this program is printing "v" as output? I understand that the commented part of the code is used to access the 3rd char of the 2nd string, but how does the first one work?

#include<stdio.h>
int main(void)
{
static char a[3][5] = {"axcd", "efgh","ijkl"};
putchar (*(*a+1)-2);
// putchar (*(*(a+1))+2);
}

1 Answer 1

1

Generally you should initialize a 2D array by double brackets, i.e

static char arr[2][3] = {{"a","b","c"},{"e","f","g"}};

To access, for example, "g" which is in the second row and third column we use:

*(arr + (1 * 3 + 2));

'arr' is address in the memory where the array is stored. '1' is the index of the wanted row, '3' is the length of each row (==number of columns). '2' is the index of the element we want in the appropriate row.

In the general case to get an element in row i and column j we use:

int arr[N][M], i, j;
... //set values for i, j..
*(arr + (i*M + j));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.