Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中修改malloc的2d数组到3d数组的函数_C_Arrays_3d_Malloc - Fatal编程技术网

在C中修改malloc的2d数组到3d数组的函数

在C中修改malloc的2d数组到3d数组的函数,c,arrays,3d,malloc,C,Arrays,3d,Malloc,我对C非常陌生,这是我用C写的第一个程序。我的教授给了我们一个为2d数组分配内存的函数,叫做malloc2d。我应该修改它来为3d数组分配内存,但是对于C来说太新了,我不知道该怎么做。我曾尝试查看其他用于3d阵列的malloc函数,但没有一个与我之前看到的类似。类似地,我们有一个free2d函数,它也需要为3d数组进行修改。以下是要修改的功能: void** malloc2D(size_t rows, size_t cols, size_t sizeOfType){ void* bloc

我对C非常陌生,这是我用C写的第一个程序。我的教授给了我们一个为2d数组分配内存的函数,叫做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

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

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

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

为了与测试修订后的二维代码的三维版本保持一致,重命名了一些修改后的代码变量:

/* 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;
}
包括怪物分配后,跟踪结束:

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行由c列组成

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

有了这个图表,或者是一个纸笔版本,上面画着箭头,level1中平面p的单元格中的值是p*行;平面p的单元格中,level2的r行的值为p*行+r*列;level3中平面p、行r、单元格c的单元格中的值为p*行+r*列+c。但这些值不是整数;它们是指针。因此,这些值必须按适当的大小进行缩放,并添加到level1、level2或level3空间的基址中

这导致了这样的代码:

#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;
}

您首先应该了解的是,您不应该盲目地信任malloc的返回值,因为它可能返回NULL,即使它几乎从不返回NULL,您也不应该假设它不会返回NULL。另外,如果自由函数的目的是防止指针悬空,那么*matrix=NULL是正确的方法。请注意,*矩阵和矩阵[0]是可互换的。告诉你的教授那是错的。它应该是char*block。我也不喜欢这种请求内存的方式,因为你不能在单元格的不同部分重新分配或释放内存,你会失去灵活性。@Pablo有趣的是,我没有注意到!
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
║ …  ║  …  ║  …  ║  …  ║  …  ║  …  ║
╚════╩═════╩═════╩═════╩═════╩═════╝
#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