C语言 我可以从二维数组中检索一维数组地址吗?



我对编程完全陌生。这段代码没有按照我想要的方式工作,即从二维数组中检索一维数组地址:

#include<stdio.h>
main() {
     int s[4][2] = {
                    { 1234, 56 },
                    { 1212, 33 },
                    { 1434, 80 },
                    { 1312, 78 }
                   };
     int i ;
     for ( i = 0 ; i <= 3 ; i++ )
         printf ( "nAddress of %d th 1-D array = %u", i, s[i] ) ;
}
#include<stdio.h>
int main( )
{
    int s[4][2] = {
                    { 1234, 56 },
                    { 1212, 33 },
                    { 1434, 80 },
                    { 1312, 78 }
                } ;
    int i ;
    for ( i = 0 ; i < 4 ; i++ )
        printf ( "nAddress of %d th 1-D array = %pn", i, (void *)s[i] ) ;
    return 0;
}

正如您在发布的代码中看到的那样,使用%p格式打印地址。此格式说明符需要void *作为传递的参数。

为了更准确地说,不使用 C 函数通过指向函数的指针传递数组(此处printf()),您可以在此处使用指向数组的指针:

for ( i = 0 ; i < 4 ; i++ ) {
    int (*ptr)[2] = &(s[i]);
    printf ( "nAddress of %d th 1-D array = %pn", i, (void*)ptr) ;
}

s[i]&(s[i]) 之间的区别在于,s[i] 1d 数组,类型是 int[2] ,其中 &(s[i]) 是指向 int[2] 的指针,您想要什么。

例如,您可以使用 sizeof 运算符看到它:此处2 * sizeof(int) sizeof(s[i]),其中sizeof(&(s[i]))具有指针变量的大小。

最新更新