【问题标题】:Is a[i] really the same as *(a + i) in C?a[i] 真的和 C 中的 *(a + i) 一样吗?
【发布时间】:2019-03-21 20:10:15
【问题描述】:
#include <stdio.h>
int sum2d(int row, int col, int p[row][col]);
int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};

    printf("%d\n", sum2d(2, 3, a));


    return 0;
}
int sum2d(int row, int col, int p[row][col])
{
    int total = 0;
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            total += (*(p + i))[j];
    return total;
}

看上面的代码。效果很好。

但是,在我把p[row]改成*(p + row)之后,

#include <stdio.h>
int sum2d(int row, int col, int (*(p + row))[col]);
int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};

    printf("%d\n", sum2d(2, 3, a));


    return 0;
}
int sum2d(int row, int col, int (*(p + row))[col])
{
    int total = 0;
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            total += (*(p + i))[j];
    return total;
}

无法编译并显示以下错误信息:

test.c:2:38: error: expected ‘)’ before ‘+’ token
 int sum2d(int row, int col, int (*(p + row))[col]);
                                      ^
test.c: In function ‘main’:
test.c:7:2: warning: implicit declaration of function ‘sum2d’ [-Wimplicit-function-declaration]
  printf("%d\n", sum2d(2, 3, a));
  ^
test.c: At top level:
test.c:12:38: error: expected ‘)’ before ‘+’ token
 int sum2d(int row, int col, int (*(p + row))[col])

以我目前的水平,我几乎看不懂。

在 C 中,我认为 a[i] = *(a + i)

为什么我的代码不正确?

【问题讨论】:

  • 您混淆了 3 个不同的术语。数组变量声明不同于函数参数声明,函数参数声明不同于使用数组的表达式。

标签: c function pointers arguments


【解决方案1】:

表达式 a[i] 等于表达式 *(a + i)。在声明中使用指针算术语法是无效的。

【讨论】:

  • ...和*(a + i) 使a[i] == i[a]!
  • @hacks puts( &amp;false["not this crap again..."] );
  • @Lundin;呵呵。顺便说一句,这肯定会产生编译错误:)
  • @hacks 如果包含 stdio.h 和 stdbool.h,则不会。完全有效的 C :)
【解决方案2】:

[] 用作后缀数组订阅运算符而不是数组声明符时,语法正确。

引用C11,第 6.5.2.1 章

后缀表达式后跟方括号中的表达式 [] 是一个下标 指定数组对象的元素。下标运算符[]的定义 是E1[E2](*((E1)+(E2))) 相同。由于转换规则 适用于二元 + 运算符,如果 E1 是一个数组对象(等效地,指向 数组对象的初始元素)和E2 是一个整数,E1[E2] 指定E2-th E1 的元素(从零开始计数)。

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 2015-08-26
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多