gpt4 book ai didi

c - C 编译器内部如何处理数组和指针类型? ( int *a; 与 int a[]; )

转载 作者:行者123 更新时间:2023-12-05 01:24:33 24 4
gpt4 key购买 nike

我需要一位有权威来源的语言律师。

看看下面的测试程序,它在 gcc 下编译得很干净:

#include <stdio.h>


void foo(int *a) {
a[98] = 0xFEADFACE;
}

void bar(int b[]) {
*(b+498) = 0xFEADFACE;
}

int main(int argc, char **argv) {

int a[100], b[500], *a_p;

*(a+99) = 0xDEADBEEF;
*(b+499) = *(a+99);

foo(a);
bar(b);

printf("a[98] == %X\na[99] == %X\n", a[98], a[99]);
printf("b[498] == %X\nb[499] == %X\n", b[498], b[499]);

a_p = a+98;
*a_p = 0xDEADFACE;

printf("a[98] == %X\na[99] == %X\n", a[98], a[99]);

}

它产生我期望的输出:

anon@anon:~/study/test_code$ gcc arrayType.c -o arrayType
anon@anon:~/study/test_code$ ./arrayType
a[98] == FEADFACE
a[99] == DEADBEEF
b[498] == FEADFACE
b[499] == DEADBEEF
a[98] == DEADFACE
a[99] == DEADBEEF

a 和 b 是同一类型吗? int *a 是否在编译器内部处理为与 int a[] 相同的类型?

从实用的角度来看,int a[100], b[500], *a_p, b_a[]; 似乎都是同一种类型。在我上面的示例中,我很难相信编译器会在各种情况下不断地调整这些类型。我很高兴被证明是错误的。

有人可以明确且详细地为我解决这个问题吗?

最佳答案

Are a and b the same type? Is int *a handled as the same type as int a[] internally in the compiler?

来自 the comp.lang.C FAQ :

... whenever an array appears in an expression, the compiler implicitly generates a pointer to the array's first element, just as if the programmer had written &a[0]. (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character array...)

... Given an array a and pointer p, an expression of the form a[i] causes the array to decay into a pointer, following the rule above, and then to be subscripted just as would be a pointer variable in the expression p[i] (although the eventual memory accesses will be different ...

Given declarations of

char a[] = "hello";
char *p = "world";

... when the compiler sees the expression a[3], it emits code to start at the location a, move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location p, fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In other words, a[3] is three places past (the start of) the object named a, while p[3] is three places past the object pointed to by p.

重点是我的。最大的区别似乎是指针是指针就取,而数组是没有指针取。

关于c - C 编译器内部如何处理数组和指针类型? ( int *a; 与 int a[]; ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1372811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com