【问题标题】:Modifying function that malloc's a 2d array to a 3d array in C在 C 中将 malloc 的 2d 数组修改为 3d 数组的函数
【发布时间】:2018-02-18 20:31:36
【问题描述】:

我对 C 很陌生,这是我用它编写的第一个程序。我的教授给了我们一个为二维数组分配内存的函数,称为 malloc2d。我应该修改它来为 3d 数组分配内存,但是对 C 来说太新了,我不知道该怎么做。我试过查看 3d 数组的其他 malloc 函数,但没有一个看起来与我得到的相似。同样,我们有一个 free2d 函数,也需要针对 3d 数组进行修改。以下是要修改的功能:

void** malloc2D(size_t rows, size_t cols, size_t sizeOfType){
    void* block = malloc(sizeOfType * rows * cols);
    void** matrix = malloc(sizeof(void*) * rows);
    for (int row = 0; row < rows; ++row) {
        matrix[row] = block + cols * row * sizeOfType;
    }//for
    return matrix;
}//malloc2D

void free2D(void*** matrix){
    free((*matrix)[0]);
    free((*matrix));
    matrix = NULL;
}//free2D

任何帮助或开始将不胜感激。

【问题讨论】:

  • 你应该学习的第一件事是你不应该盲目相信malloc()的返回值,因为它可能会返回NULL,即使它几乎从来没有,你也不应该假设它不会。此外,如果您的free() 函数的目的是防止出现悬空指针,那么*matrix = NULL 是正确的方法。请注意,*matrixmatrix[0] 可以互换。
  • 还有void* pointer arithmetic is illegal。告诉你的教授这是错误的。应该是char *block
  • 另外我不喜欢这种请求内存的方式,因为你不能在单元格的不同部分重新分配或释放内存,你会失去灵活性。
  • @Pablo 有趣,我没注意到!

标签: c arrays 3d malloc


【解决方案1】:

我很难相信这是第一次练习;至少,这有点棘手。

修复二维码

第一步应该是清理malloc2D()函数,这样它就不会随便使用GCC扩展——索引void *——因为标准C不允许这样做(因为sizeof(void)在标准C中是未定义的; GNU C 将其定义为 1)。另外,free2D() 中的 bug 需要修复;函数的最后一行应为*matrix = NULL;(省略了*)。该代码也应该进行测试,因为访问矩阵的正确方法并不明显。

这里有一些修改后的代码(变量重命名以与 3D 版本保持一致),用于测试修改后的 2D 代码:

/* SO 4885-6272 */

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

/* Should be declared in a header for use in other files */
extern void **malloc2D(size_t rows, size_t cols, size_t sizeOfType);
extern void free2D(void ***matrix);

void **malloc2D(size_t rows, size_t cols, size_t sizeOfType)
{
    void *level2 = malloc(sizeOfType * rows * cols);
    void **level1 = malloc(sizeof(void *) * rows);
    if (level2 == NULL || level1 == NULL)
    {
        free(level2);
        free(level1);
        return NULL;
    }
    for (size_t row = 0; row < rows; ++row)
    {
        level1[row] = (char *)level2 + cols * row * sizeOfType;
    }
    return level1;
}

void free2D(void ***matrix)
{
    free((*matrix)[0]);
    free((*matrix));
    *matrix = NULL;
}

static void test2D(size_t m2_rows, size_t m2_cols)
{
    printf("rows = %zu; cols = %zu\n", m2_rows, m2_cols);
    void **m2 = malloc2D(m2_rows, m2_cols, sizeof(double));
    if (m2 == NULL)
    {
        fprintf(stderr, "Memory allocation failed for 2D array of size %zux%zu doubles\n",
                m2_rows, m2_cols);
        return;
    }

    printf("m2 = 0x%.12" PRIXPTR "; m2[0] = 0x%.12" PRIXPTR "\n",
           (uintptr_t)m2, (uintptr_t)m2[0]);

    for (size_t i = 0; i < m2_rows; i++)
    {
        for (size_t j = 0; j < m2_cols; j++)
            ((double *)m2[i])[j] = (i + 1) * 10 + (j + 1);
    }

    for (size_t i = 0; i < m2_rows; i++)
    {
        for (size_t j = 0; j < m2_cols; j++)
            printf("%4.0f", ((double *)m2[i])[j]);
        putchar('\n');
    }

    free2D(&m2);
    printf("m2 = 0x%.16" PRIXPTR "\n", (uintptr_t)m2);
}

int main(void)
{
    test2D(4, 5);
    test2D(10, 3);
    test2D(3, 10);
    //test2D(300000000, 1000000000);  /* 2132 PiB - should fail to allocate on sane systems! */
    return 0;
}

在运行 macOS High Sierra 10.13.3 并使用 GCC 7.3.0 编译的 MacBook Pro 上运行时,我得到以下输出:

rows = 4; cols = 5
m2 = 0x7F83C04027F0; m2[0] = 0x7F83C0402750
  11  12  13  14  15
  21  22  23  24  25
  31  32  33  34  35
  41  42  43  44  45
m2 = 0x0000000000000000
rows = 10; cols = 3
m2 = 0x7F83C0402750; m2[0] = 0x7F83C04028C0
  11  12  13
  21  22  23
  31  32  33
  41  42  43
  51  52  53
  61  62  63
  71  72  73
  81  82  83
  91  92  93
 101 102 103
m2 = 0x0000000000000000
rows = 3; cols = 10
m2 = 0x7F83C04027A0; m2[0] = 0x7F83C04028C0
  11  12  13  14  15  16  17  18  19  20
  21  22  23  24  25  26  27  28  29  30
  31  32  33  34  35  36  37  38  39  40
m2 = 0x0000000000000000

加上怪物分配,追踪结束:

alloc3d19(8985,0x7fffa5d79340) malloc: *** mach_vm_map(size=2400000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Memory allocation failed for 2D array of size 300000000x1000000000 doubles

适应3D码

我选择将 3D 数组的前导维度称为“平面”;每个平面都包含一个二维数组,其中 r 行 x c 列。

对我来说,我给自己画了一个图表,以说服自己我做的作业是正确的——在我搞砸了几次之后。在前两个表的每个单元格中,第一个数字是包含数组中的单元格的索引号(第一个表中的level1),第二个是下一级单元格的索引号(level2在第一个表中)。 level3 表中的数字只是doublea 数组的索引。

level1 (planes: 4)
╔═══════╗
║ 0: 00 ║
║ 1: 05 ║
║ 2: 10 ║
║ 3: 15 ║
╚═══════╝

level2 (planes: 4; rows: 5)
╔════════╦════════╦════════╦════════╦════════╗
║ 00: 00 ║ 01: 06 ║ 02: 12 ║ 03: 18 ║ 04: 24 ║
║ 05: 30 ║ 06: 36 ║ 07: 42 ║ 08: 48 ║ 09: 54 ║
║    …   ║    …   ║    …   ║    …   ║    …   ║
╚════════╩════════╩════════╩════════╩════════╝

level3 (planes: 4; rows: 5; cols: 6)
╔════╦═════╦═════╦═════╦═════╦═════╗
║  0 ║   1 ║   2 ║   3 ║   4 ║   5 ║
║  6 ║   7 ║   8 ║   9 ║  10 ║  11 ║
║ 12 ║  13 ║  14 ║  15 ║  16 ║  17 ║  Plane 0
║ 18 ║  19 ║  20 ║  21 ║  22 ║  23 ║
║ 24 ║  25 ║  26 ║  27 ║  28 ║  29 ║
╠════╬═════╬═════╬═════╬═════╬═════╣
║ 30 ║  31 ║  32 ║  33 ║  34 ║  35 ║
║ 36 ║  37 ║  38 ║  39 ║  40 ║  41 ║  Plane 1
║ …  ║  …  ║  …  ║  …  ║  …  ║  …  ║
╚════╩═════╩═════╩═════╩═════╩═════╝

有了那个图表——或者是纸笔版本,上面有潦草的箭头,level1中平面p的单元格中的值是p * rows;平面p,行rlevel2的单元格中的值是p * rows + r) * colslevel3 中平面p、行rc 的单元格中的值是(p * rows + r) * cols + c。但是这些值不是整数;他们是指针。因此,这些值必须按适当的大小缩放并添加到level1level2level3 空间的基地址。

这导致这样的代码:

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

/* Should be declared in a header for use in other files */
extern void ***malloc3D(size_t planes, size_t rows, size_t cols, size_t sizeOfType);
extern void free3D(void ****matrix);

void ***malloc3D(size_t planes, size_t rows, size_t cols, size_t sizeOfType)
{
    void   *level3 = malloc(sizeOfType * planes * rows * cols);
    void  **level2 = malloc(sizeof(void *) * planes * rows);
    void ***level1 = malloc(sizeof(void **) * planes);
    //printf("planes = %zu; rows = %zu; cols = %zu; ", planes, rows, cols);
    //printf("level1 = 0x%.12" PRIXPTR "; level2 = 0x%.12" PRIXPTR "; level3 = 0x%.12" PRIXPTR "\n",
    //        (uintptr_t)level1, (uintptr_t)level2, (uintptr_t)level3);
    fflush(stdout);
    if (level3 == NULL || level2 == NULL || level1 == NULL)
    {
        free(level3);
        free(level2);
        free(level1);
        return NULL;
    }
    for (size_t plane = 0; plane < planes; plane++)
    {
        level1[plane] = (void **)((char *)level2 + plane * rows * sizeof(void **));
        //printf("level1[%zu]   = 0x%.12" PRIXPTR "\n", plane, (uintptr_t)level1[plane]);
        for (size_t row = 0; row < rows; ++row)
        {
            level2[plane * rows + row] = (char *)level3 + (plane * rows + row) * cols * sizeOfType;
            //printf("  level2[%zu] = 0x%.12" PRIXPTR "\n",
            //       plane * rows + row, (uintptr_t)level2[plane * rows + row]);
        }
    }
    return level1;
}

void free3D(void ****matrix)
{
    free((*matrix)[0][0]);
    free((*matrix)[0]);
    free((*matrix));
    *matrix = NULL;
}

static void test3D(size_t m3_plns, size_t m3_rows, size_t m3_cols)
{
    printf("planes = %zu; rows = %zu; cols = %zu\n", m3_plns, m3_rows, m3_cols);
    void ***m3 = malloc3D(m3_plns, m3_rows, m3_cols, sizeof(double));
    if (m3 == NULL)
    {
        fprintf(stderr, "Memory allocation failed for 3D array of size %zux%zux%zu doubles\n",
                m3_plns, m3_rows, m3_cols);
        return;
    }

    printf("m3 = 0x%.12" PRIXPTR "; m3[0] = 0x%.12" PRIXPTR "; m3[0][0] = 0x%.12" PRIXPTR "\n",
           (uintptr_t)m3, (uintptr_t)m3[0], (uintptr_t)m3[0][0]);

    for (size_t i = 0; i < m3_plns; i++)
    {
        for (size_t j = 0; j < m3_rows; j++)
        {
            for (size_t k = 0; k < m3_cols; k++)
                ((double *)m3[i][j])[k] = (i + 1) * 100 + (j + 1) * 10 + (k + 1);
        }
    }

    for (size_t i = 0; i < m3_plns; i++)
    {
        printf("Plane %zu:\n", i + 1);
        for (size_t j = 0; j < m3_rows; j++)
        {
            for (size_t k = 0; k < m3_cols; k++)
                printf("%4.0f", ((double *)m3[i][j])[k]);
            putchar('\n');
        }
        putchar('\n');
    }

    free3D(&m3);
    printf("m3 = 0x%.16" PRIXPTR "\n", (uintptr_t)m3);
}

int main(void)
{
    test3D(4, 5, 6);
    test3D(3, 4, 10);
    test3D(4, 3, 7);
    test3D(4, 9, 7);
    test3D(30000, 100000, 100000000);  /* 2132 PiB - should fail to allocate on sane systems! */
    return 0;
}

示例输出(内存分配过大):

planes = 4; rows = 5; cols = 6
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402850
Plane 1:
 111 112 113 114 115 116
 121 122 123 124 125 126
 131 132 133 134 135 136
 141 142 143 144 145 146
 151 152 153 154 155 156

Plane 2:
 211 212 213 214 215 216
 221 222 223 224 225 226
 231 232 233 234 235 236
 241 242 243 244 245 246
 251 252 253 254 255 256

Plane 3:
 311 312 313 314 315 316
 321 322 323 324 325 326
 331 332 333 334 335 336
 341 342 343 344 345 346
 351 352 353 354 355 356

Plane 4:
 411 412 413 414 415 416
 421 422 423 424 425 426
 431 432 433 434 435 436
 441 442 443 444 445 446
 451 452 453 454 455 456

m3 = 0x0000000000000000
planes = 3; rows = 4; cols = 10
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402840
Plane 1:
 111 112 113 114 115 116 117 118 119 120
 121 122 123 124 125 126 127 128 129 130
 131 132 133 134 135 136 137 138 139 140
 141 142 143 144 145 146 147 148 149 150

Plane 2:
 211 212 213 214 215 216 217 218 219 220
 221 222 223 224 225 226 227 228 229 230
 231 232 233 234 235 236 237 238 239 240
 241 242 243 244 245 246 247 248 249 250

Plane 3:
 311 312 313 314 315 316 317 318 319 320
 321 322 323 324 325 326 327 328 329 330
 331 332 333 334 335 336 337 338 339 340
 341 342 343 344 345 346 347 348 349 350

m3 = 0x0000000000000000
planes = 4; rows = 3; cols = 7
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402750; m3[0][0] = 0x7FFCC9402840
Plane 1:
 111 112 113 114 115 116 117
 121 122 123 124 125 126 127
 131 132 133 134 135 136 137

Plane 2:
 211 212 213 214 215 216 217
 221 222 223 224 225 226 227
 231 232 233 234 235 236 237

Plane 3:
 311 312 313 314 315 316 317
 321 322 323 324 325 326 327
 331 332 333 334 335 336 337

Plane 4:
 411 412 413 414 415 416 417
 421 422 423 424 425 426 427
 431 432 433 434 435 436 437

m3 = 0x0000000000000000
planes = 4; rows = 9; cols = 7
m3 = 0x7FFCC94027F0; m3[0] = 0x7FFCC9402840; m3[0][0] = 0x7FFCC9802000
Plane 1:
 111 112 113 114 115 116 117
 121 122 123 124 125 126 127
 131 132 133 134 135 136 137
 141 142 143 144 145 146 147
 151 152 153 154 155 156 157
 161 162 163 164 165 166 167
 171 172 173 174 175 176 177
 181 182 183 184 185 186 187
 191 192 193 194 195 196 197

Plane 2:
 211 212 213 214 215 216 217
 221 222 223 224 225 226 227
 231 232 233 234 235 236 237
 241 242 243 244 245 246 247
 251 252 253 254 255 256 257
 261 262 263 264 265 266 267
 271 272 273 274 275 276 277
 281 282 283 284 285 286 287
 291 292 293 294 295 296 297

Plane 3:
 311 312 313 314 315 316 317
 321 322 323 324 325 326 327
 331 332 333 334 335 336 337
 341 342 343 344 345 346 347
 351 352 353 354 355 356 357
 361 362 363 364 365 366 367
 371 372 373 374 375 376 377
 381 382 383 384 385 386 387
 391 392 393 394 395 396 397

Plane 4:
 411 412 413 414 415 416 417
 421 422 423 424 425 426 427
 431 432 433 434 435 436 437
 441 442 443 444 445 446 447
 451 452 453 454 455 456 457
 461 462 463 464 465 466 467
 471 472 473 474 475 476 477
 481 482 483 484 485 486 487
 491 492 493 494 495 496 497

m3 = 0x0000000000000000
planes = 30000; rows = 100000; cols = 100000000
alloc3d79(9018,0x7fffa5d79340) malloc: *** mach_vm_map(size=2400000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Memory allocation failed for 3D array of size 30000x100000x100000000 doubles

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2015-03-06
    • 1970-01-01
    • 2017-07-26
    • 2016-06-01
    • 2017-09-18
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多