【问题标题】:C: Address of (c)allocated array does not fit with size of data type (I think....)C:(c)分配数组的地址不适合数据类型的大小(我认为....)
【发布时间】:2015-11-26 20:04:53
【问题描述】:

以下代码应该为二维数组分配一些内存。我将它们的值和地址打印到屏幕上,但对输出感到困惑......

这是 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 字节,依此类推。

我做错了什么,是我打印地址的方式吗?

【问题讨论】:

  • 转换为 size_t 是多余的,因为 C 具有整数类型之间的隐式转换。
  • 不是您的实际问题,但从 C99 开始,您可以使用带有数组语法的单个 malloc,而不是设置这个提供语法糖的行指针表
  • @M.M hmm.... 你的意思是像(*arr)[N_cols] = calloc(N_rows * N_cols, sizeof **arr )
  • 是这样的
  • 这一行:arr[0] = calloc( (size_t)(N_rows*N_cols), sizeof **arr );需要是一个循环,每行调用一次calloc(),类似这样:for( int i=0;i&lt;N_rows; i++ ) { arr[i] = calloc( N_cols, sizeof( double ) ); } Then the pointers are already set and the correct amounts of allocated memory gotten. Then the row pointers need to be passed to free()`在一个循环中

标签: c arrays pointers malloc calloc


【解决方案1】:

地址以 8 个字节递增。它们是十六进制

0x12dc030
0x12dc038 - difference of 8 from the above
0x12dc040 - difference of 8 from the above

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2017-12-06
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2016-07-07
    • 2021-08-19
    相关资源
    最近更新 更多