c - 二维数组的问题

标签 c arrays pointers 2d

我用C写了下面的代码:

#include<stdio.h>

int  main()
{
  int a[10][10]={1};
  //------------------------
  printf("%d\n",&a);
  printf("%d\n",a);
  printf("%d\n",*a);
  //-------------------------
  printf("%d",**a);

  return 0;
}

通过上面的 3 个 printf 语句,我得到了相同的值。在我的机器上它是 2686384。但是最后一条语句我得到了 1。

是不是出了什么问题?这些陈述意味着:

  1. a的地址是2686384
  2. a中存储的值为2686384
  3. a 指向的变量地址(即 2686384)存储的值为 2686384。

这意味着 a 必须类似于指向自身的变量...

那为什么*(*a)的输出是1呢?为什么不将其计算为 *(*a)=*(2686384)=2686384

最佳答案

#include<stdio.h>

int  main()
{
  // a[row][col]
  int a[2][2]={ {9, 2}, {3, 4} };
  // in C, multidimensional arrays are really one dimensional, but
  // syntax alows us to access it as a two dimensional (like here).

  //------------------------
  printf("&a            = %d\n",&a);
  printf("a             = %d\n",a);
  printf("*a            = %d\n",*a);
  //-------------------------

  // Thing to have in mind here, that may be confusing is:
  // since we can access array values through 2 dimensions,
  // we need 2 stars(asterisk), right? Right.

  // So as a consistency in this aproach,
  // even if we are asking for first value,
  // we have to use 2 dimensional (we have a 2D array)
  // access syntax - 2 stars.

  printf("**a           = %d\n", **a );         // this says a[0][0] or *(*(a+0)+0)
  printf("**(a+1)       = %d\n", **(a+1) );     // a[1][0] or *(*(a+1)+0)
  printf("*(*(a+1)+1)   = %d\n", *(*(a+1)+1) ); // a[1][1] or *(*(a+1)+1)
  // a[1] gives us the value on that position,
  // since that value is pointer, &a[i] returns a pointer value
  printf("&a[1]         = %d\n", &a[1]);
  // When we add int to a pointer (eg. a+1),
  // really we are adding the lenth of a type
  // to which pointer is directing - here we go to the next element in an array.

  // In C, you can manipulate array variables practically like pointers.
  // Example: littleFunction(int [] arr) accepts pointers to int, and it works vice versa,
  //          littleFunction(int* arr) accepts array of int.

  int b = 8;
  printf("b             = %d\n", *&b);

  return 0;

}

关于c - 二维数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12529484/

相关文章:

c - strlen(string) 和 strlen(*string) 之间的区别

c# - 在 C# 中用另一个对象实例替换对象实例

c - 删除 char*,同时保留字符串

Case 标签不会缩减为 C 中的整数常量?

c++ - 使用 Mergesort 计算 C++ 中的反转次数

javascript - 检查字符串是否以前缀开头

c - 在我的考试中嵌套 printf

c - 链表的具体排序

java - 最终字符串[]和最终字符串

C++ 地址和指针