1

I am trying to print a 2D array by passing it to a function, but I got weird results. Here is my code.

#include <stdio.h>

int main()
{
    int b[2][3] = {{1,2,3},{4,5,6}};
    printArray(b);
    return 0;
}

void printArray(int (*ptr)[3])
{
    int i, j;
    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 3; j++)
        {
            printf("%d\t", *((*ptr+i)+j));
        }
        printf("\n");
    }
}

However, the output is

1  2   3

2  3   4

I think it is something to do with my 'j' variable but I can't seem to pinpoint it. Please help.

4 Answers 4

1

You need to apply the addition operator before using the dereference operator. You need to use parenthesis as the dereference operator(*) has higher precedence than the addition operator(+).

So, this

printf("%d\t", *((*ptr+i)+j));

should be

printf("%d\t", *((*(ptr+i))+j));

or better

printf("%d\t", ptr[i][j]);

Also, you need to move the function printArray before main or provide a function prototype before main like:

void printArray(int (*ptr)[3]);
Sign up to request clarification or add additional context in comments.

Comments

1

You need to multiply i by 3 before adding j ...

printf("%d\t", *((*ptr+(i*3))+j));

Comments

0

Abandoning indexes in favor of pointers, assuming matrix is stored by rows (whic is normally the case):

#include <stdio.h>

void printArray(int *);

int main()
{
 int b[2][3] = {{1,2,3},{4,5,6}};
 printArray((int*)b);
 return 0;
}

void printArray(int *ptr)
{
int i, j;
 for(i = 0; i < 2; i++)
 {
    for(j = 0; j < 3; j++)
    {
     printf("%d\t", *ptr++);
    }
  printf("\n");
 }
}

Outputs:

1   2   3   
4   5   6

Comments

0

printArray can take nb_column nb_line param and deal with all sort of 2D array

#include <stdio.h> 

static void printArray(int *ptr,  int nb_columns, int nb_lines) 
{ 
    int i, j; 
    for(i = 0; i < nb_lines; i++) 
    { 
        for(j = 0; j < nb_columns; j++) 
        { 
            printf("%d\t", *(ptr++)); 
        } 
        printf("\n"); 
    } 
} 
int main() 
{ 
    int b[2][3] = {{1,2,3},{4,5,6}}; 
    printArray((int *)b, 3, 2); 
    return 0; 
} 

1 Comment

Is it safe to cast an int(*)[3] into an int*?

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.