理解C语言中关于数组地址值的两个程序

程序1:

#include <stdio.h>

char ga[] = "abcdefghijklm";

void my_array_func(char ca[10]) {
    printf("%#x, %d\n", &ca, sizeof(ca));
    printf("%#x\n", &(ca[0]));
    printf("%#x\n", &(ca[1]));
    printf("%#x\n\n", ++ca);
}

void my_poiner_func(char *pa) {
    printf("%#x, %d\n", &pa, sizeof(pa));
    printf("%#x\n", &(pa[0]));
    printf("%#x\n", &(pa[1]));
    printf("%#x\n\n", ++pa);
}

int main(void) {
    printf("%#x\n", &ga);
    printf("%#x\n", &(ga[0]));
    printf("%#x\n\n", &(ga[1]));
    my_array_func(ga);
    my_poiner_func(ga);
    return 0;
}

运行结果:

0x804987c
0x804987c
0x804987d

0xff95b040, 4
0x804987c
0x804987d
0x804987d

0xff95b040, 4
0x804987c
0x804987d
0x804987d

参考Passing an array as an argument to a function in C

程序2:

#include <stdio.h>

int main(void) {
    // your code goes here
    int array[5];
    printf("%p, %d\n", array, sizeof(array));
    printf("%p, %d\n", &array[0], sizeof(&array[0]));
    printf("%p, %d\n", &array, sizeof(&array));
    printf("%p\n", array + 1);
    printf("%p\n", &array[0] + 1);
    printf("%p\n", &array + 1);
    return 0;
}

运行结果:

0xffd062ec, 20
0xffd062ec, 4
0xffd062ec, 4
0xffd062f0
0xffd062f0
0xffd06300

参考How come an array’s address is equal to its value in C?

发表评论

电子邮件地址不会被公开。 必填项已用*标注