1

If you want to fill a matrix in C, you can use index, like this:

#include<stdio.h>

int main(){

    char m[20][30];

    int i = 0;
    int j = 0;

    while(i <= 20){
        j=0;
        while(j <= 30){

            m[i][j] = 's';
            printf("%c", m[i][j]);
            j++;

        }
        printf("\n");
        i++;
    }
}

but how can I do this with pointers?

munk
  • 12,340
  • 8
  • 51
  • 71
gMendeZm
  • 185
  • 1
  • 1
  • 9
  • 1
    first of all this is getting out of bounds... `i <= 20` should be `i < 20` and `j <= 30` should be `j < 30` – chrk Mar 01 '14 at 23:47
  • Depends, you mean that you want to stock pointers in your matrix or to access your matrix with pointers ? – Antoine C. Mar 02 '14 at 00:00

2 Answers2

2

In your case:

To use a pointer:

char m[20][30];
char *ptr; // Your pointer 
ptr=m; // point ptr to the location where m points to 

Now, replace

m[i][j] = 's';
printf("%c", m[i][j]);

with

*((char *)ptr + (i * 30) + j) = 's';
    printf("%c", *((char *)ptr + (i * 30) + j));

Why this works?

For 1-D array:

 int a[10];

You can access it like:

a[1]; //Say the 2nd element

So, in terms of pointers, this is equivalent to:

*((int*)a+1).

For 2-D arrays:

int b[NO_OF_ROWS][NO_OF_COLUMNS];

In generalized form, assume any elment:

b[r][c]; // let r < NO_OF_ROWS, c < NO_OF_COLUMNS be any index

is equivalent to

*((int *)b + r * NO_OF_COLUMNS  + c);
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

I think that the reason of using pointers instead [] operator is it's a bit faster (in theory, anyway)... In this case, I think you want this..

#include <stdio.h>

int main()
{
    char m[20][30];

    char (*ptr1)[30];
    char *ptr2;

    for (ptr1 = m; ptr1 < m + sizeof(m) / sizeof(m[0]); ptr1++)
    {
        for (ptr2 = *ptr1; ptr2 < *ptr1 + sizeof(*ptr1) / sizeof((*ptr1)[0]); ptr2++)
        {
            *ptr2 = 's';
            printf("%c", *ptr2);
        }
        printf("\n");
    }
}
ikh
  • 10,119
  • 1
  • 31
  • 70