【问题标题】:How use correctly the pointers in a multi dimensional array?如何正确使用多维数组中的指针?
【发布时间】:2016-10-23 08:35:28
【问题描述】:

我必须创建一个矩阵并只用一个指针来操作它

我的代码:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void Matrix();
int Fun(int *A, int n, int key);

int main()
{
 Matrix();
 return 0;
}

void Matrix()
{
  int Nel, Larray, i, j, k, a, c, b, Nf;
  printf("Num of elements: ");
  scanf("%d", &Nel);

  int A[Nel][Nel];

    srand(time(NULL));
    for(b=0;b<Nel;b++)
    {
      for(c=0;c<Nel;c++)
      {
          A[b][c] = rand() % 100 + 1;
      }
    }

    printf("\n");

    for(b=0;b<Nel;b++)
    {
      for(c=0;c<Nel;c++)
      {
          printf("%d\t",A[b][c]);
      }
      printf("\n");
    }
    printf("\n\n");

    printf("Num to find? ");
    scanf("%d", &Nf);

     Fun(*A, Nel, Nf);
 }//end


 int Fun(int *A, int n, int key)
 {
   //just to see if it works
   int i,j;

   for(i=0;i<n;i++)
   {
     for(j=0;j<n;j++)
     {
      printf("%d\t",A);
      }
    printf("\n");
   }
 }

在函数Fun中,给我一个错误

printf("%d\t",A); subscripted value is neither array nor pointer nor vector

我只需要使用一个指针来调用矩阵。 你能解释多维数组中的指针算法吗?谢谢

【问题讨论】:

    标签: c arrays pointers multidimensional-array


    【解决方案1】:

    假设您有 int* arr; 指向大小为 [ROWS_NUM][COLS_NUM] 的数组,则尝试访问 arr[X][Y] 时完成的计算是 arr + (X * COLS_NUM + Y)

    一般规则是多维数组中元素的绝对索引为absolute_index = ((index1 * size2 + index2) * size3 + index3) * size4 + index4 .....(您只需在其中添加数组的偏移量)。

    您可以查看此草图以了解多维数组在内存中的格式化方式:

    【讨论】:

    • 这很清楚,但我该如何解决我的问题?使用 2 个指针我没有问题,但我必须只使用一个指针!
    • printf("%d\t",A) 替换为printf ("%d\t",*(A+(i*n+j)))printf ("%d\t",A[i*n+j]),如果有帮助,请将答案标记为已解决。
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    相关资源
    最近更新 更多