以下代码应该为2D数组分配一些内存。我将它们的值和地址打印到屏幕上,但对输出感到困惑......
这是C代码:
#include <stdio.h>
#include <stdlib.h>
void print_2Darr( double **arr_2D, int N_rows, int N_cols );
int main(){
int ii;
const int N_cols = 4;
const int N_rows = 3;
double
**arr;
// note: for readibility, checking for NULL is omitted
// allocate pointer to rows, then rows...
arr = calloc( (size_t)N_rows, sizeof *arr );
arr[0] = calloc( (size_t)(N_rows*N_cols), sizeof **arr );
// ... and set pointers to them
for ( ii=1 ; ii<N_rows ; ++ii )
arr[ii] = arr[ii-1] + N_cols;
// print values their address of them
print_2Darr( arr, N_rows, N_cols );
// not to be forgotten...
free( arr[0] );
free( arr );
return EXIT_SUCCESS;
}
void print_2Darr( double **arr_2D, int N_rows, int N_cols ) {
int
ii, jj;
for ( ii=0 ; ii<N_rows ; ++ii) {
for ( jj=0 ; jj<N_cols; ++jj)
printf( "%f (%p)\t", arr_2D[ii][jj], (void*)&arr_2D[ii][jj] );
printf( "\n" );
}
}
现在是关键部分,输出可能如下所示:
0.000000 (0x12dc030) 0.000000 (0x12dc038) 0.000000 (0x12dc040) 0.000000 (0x12dc048)
0.000000 (0x12dc050) 0.000000 (0x12dc058) 0.000000 (0x12dc060) 0.000000 (0x12dc068)
0.000000 (0x12dc070) 0.000000 (0x12dc078) 0.000000 (0x12dc080) 0.000000 (0x12dc088)
我原以为通过数组走8字节会更高。显然,这仅适用于每第二步(从第0个元素到第1个,然后从第2个到第3个等)。地址前进8字节,然后是2字节,然后是8字节,然后是2字节,依此类推。
我做错了什么,是我打印地址的方式?
答案 0 :(得分:4)
地址ARE增加8个字节。它们位于 hex 。
0x12dc030
0x12dc038 - difference of 8 from the above
0x12dc040 - difference of 8 from the above