C: (c) 分配数组的地址不适合数据类型的大小(我认为....)
C: Address of (c)allocated array does not fit with size of data type (I think....)
下面的代码应该为二维数组分配一些内存。我将它们的值和地址打印到屏幕上,但对输出感到困惑...
这是 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个字节等等。
我做错了什么,是我打印地址的方式吗?
地址递增 8 个字节。它们在 hex.
0x12dc030
0x12dc038 - difference of 8 from the above
0x12dc040 - difference of 8 from the above
下面的代码应该为二维数组分配一些内存。我将它们的值和地址打印到屏幕上,但对输出感到困惑...
这是 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个字节等等。
我做错了什么,是我打印地址的方式吗?
地址递增 8 个字节。它们在 hex.
0x12dc030
0x12dc038 - difference of 8 from the above
0x12dc040 - difference of 8 from the above