While solving the problem using the array pointer, I had a question

Asked 1 years ago, Updated 1 years ago, 122 views

#include<stdio.h>

void rotate(int(*ptr)[4])
{
    int i,j;
    int temp[4][4];
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            temp[i][j]=ptr[3-j][i];
        }
    }
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            ptr[i][j]=temp[i][j];
        }
    }
}

void howmanytimes(int n,void(*ptr1)(int(*ptr2)[4]))
{
    int i=0;
    int a,b;
    while(i<n)
    {
        ptr1(ptr2);
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            {
                printf("%1d",ptr2[a][b]);
            }
            printf("\n");
        }
        printf("\n");
        i++;
    }
}
int main(void)
{
    int arr[4][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int num=2;
    printf ("How many turns will you make?"");
    howmanytimes(num,rotate(arr));
    return 0;
}

In an int-type two-dimensional array of 4x4, we're going to create a program source that moves the elements 90 degrees to the right and outputs each of the results, and I'm not sure which parts are wrong in the execution ㅠ<

pointer array call-by-reference

2022-09-21 17:30

2 Answers

I think you wrote the function pointer a little weird, so I modified the code a little bit. I don't know how C compiler works these days, so I only changed the code so that the "code executor" recognizes it.

void rotate(int(*ptr)[4]) { int i,j; int temp[4][4]; for(i=0;i<4;i++) { for(j=0;j<4;j++) { temp[i][j]=ptr[3-j][i]; } } for(i=0;i<4;i++) { for(j=0;j<4;j++) { ptr[i][j]=temp[i][j]; } } }

void howmanytimes(int n,void(function)(int()[4]), int(*ptr2)[4]) { int i=0; int a,b; while(i<n) { function(ptr2); for(a=0;a<4;a++) { for(b=0;b<4;b++) { printf("%02d ",ptr2[a][b]); } printf("\n"); } printf("\n"); i++; } }

int main(void) { int arr[4][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int num=1;

howmanytimes(num,&rotate,arr);
return 0;

}


2022-09-21 17:30

I think you didn't mean to use a function pointer, so I modified it at least.

#include <stdio.h>

void rotate(int (*arr)[4]) {
  int i, j;
  int temp[4][4];
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
      temp[i][j] = arr[3 - j][i];
    }
  }
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
      arr[i][j] = temp[i][j];
    }
  }
}

void howmanytimes(int n, int (*arr)[4]) {
  n = (n & 3);
  for (int i = 0; i < n; i++) {
    rotate(arr);
  }
  for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4; j++) {
      printf("%02d ", arr[i][j]);
    }
    printf("\n");
  }
  printf("\n");
}

int main(void) {
  int arr[4][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
  int num = 2;
  printf ("How many turns will you make?"");
  return 0;
}


2022-09-21 17:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.