Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetic and 2-D array in c?

I am new to C and got stuck on "How to pass multidimensional array to a function". I do understand that you have to pass column size so that if you want to go from a[0][0] to a[1][0] it can calculate the size of 1-D array and can jump over it.

I have written a small program:

#include<stdio.h>
void foo(char[][2]);
int main()
{
     char arr[2][2] = {'a','b','c','d'};

     foo(arr);
     return 0;
}

void foo(char temp[][2])
{
      temp++;
      printf("%c",*temp);
}

I expected that this code will print the letter c, since temp initially points to 'a' and once we increment it, it will skip over first 1-d array and go to first element of second 1-d array which is 'c'. But it does not work that way I guess.

Please explain the how compiler computes these addresses.

like image 891
mightyWOZ Avatar asked May 19 '26 06:05

mightyWOZ


1 Answers

The pointer arithmetic is good. You just forgot to dereference *temp, which has type char[2].

Change it to **temp, and you'll get an output c.

like image 154
MikeCAT Avatar answered May 21 '26 20:05

MikeCAT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!