However, every time I reference own[i][j], I get an error saying that the subscripted value is neither array nor pointer nor vector.

That's right. own[i] is equivalent to *(own + i), which has type int. You cannot apply the subscript operator to an int.

Note that what your code appears to be trying to create is not a two-dimensional array, but rather an array of pointers. If that's really what you want then own should have type int **, and you should adjust the first calloc() call accordingly. If you really want dynamic allocation of a 2D array, though, then that would be:

int (*own)[3];

own = calloc(mem_size, sizeof(*own));

Note that there is no need then to allocate (or free) the rows separately.

Note also, however, that if you do not ever need to reallocate own before it goes out of scope, if you can assume at least a C99 compiler, and if mem_size is will never be too large then you can do this even more easily via a variable-length array:

int own[mem_size][3] = {{0}};

No explicit dynamic allocation or deallocation is needed at all in that case, and the initializer can be omitted if unneeded. (I include the initializer because calloc() performs equivalent initialization of the allocated space.) "Too large" should be interpreted in relation to the array being allocated on the stack.

Answer from John Bollinger on Stack Overflow
🌐
Nus
phyweb.physics.nus.edu.sg › ~phywjs › CZ1102 › lecture20 › tsld014.htm
Two-dimensional array with calloc
Define a pointer to pointer to double: double **b; Allocate a one-dimensional array of pointers to double b = (double **) calloc(100, sizeof(double*)); For each of the pointer to double, allocate an array of double, let the pointer pointing to it. for(i = 0; i &#060 100; ++i) { b[i] = (double ...
Discussions

c - Multidimensional arrays allocated through calloc - Stack Overflow
I have a question about how memory is allocated when I calloc. I had a look at this question, but it doesn't address how memory is allocated in the case of a dynamically allocated two dimensional array. I was wondering if there was a difference in the memory representation between the following three ways of dynamically allocating a 2D ... More on stackoverflow.com
🌐 stackoverflow.com
malloc() question for 2d array
sizeof board tells you the size of board. If board is a pointer, then sizeof board is the size of the pointer, which is eight bytes on your machine. If board is an array, then sizeof board is the size of the array. You can't get the size of the malloced region from the pointer it returns. No size information is encoded in a pointer; all a pointer does is point to some single position in memory. More on reddit.com
🌐 r/C_Programming
28
2
November 8, 2020
c - How to calloc a 2D array without valgrind errors? - Stack Overflow
I am working on a school project, trying to create a 2d array based on variables. int **wagner; wagner = (int **)calloc((sizeofvstup1 + 1), sizeof(int)); for (int i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
c++ - 2d array, using calloc in C - Stack Overflow
I'm trying to create a 2D array of chars to storage lines of chars. For Example: lines[0]="Hello"; lines[1]="Your Back"; lines[2]="Bye"; Since lines has to be dynamically cause i don't know how many lines i need at first. Here is the code i have: int i; char **lines= (char**) calloc(size, ... More on stackoverflow.com
🌐 stackoverflow.com
April 19, 2010
🌐
GeeksforGeeks
geeksforgeeks.org › c language › dynamically-allocate-2d-array-c
How to dynamically allocate a 2D array in C? - GeeksforGeeks
January 10, 2025 - #include <stdio.h> #include <stdlib.h> int main() { int row = 3, col = 4, i, j, count; int (*arr)[col] = calloc(row, sizeof *arr); count = 0; for (i = 0; i < row; i++) for (j = 0; j < col; j++) arr[i][j] = ++count; for (i = 0; i < row; i++) for (j = 0; j < col; j++) printf("%d ", arr[i][j]); free(arr); return 0; } Output · 1 2 3 4 5 6 7 8 9 10 11 12 · Comment · Article Tags: Article Tags: C Language · cpp-array ·
🌐
Nus-cs1010
nus-cs1010.github.io › 1819-s1 › 19-md-array.html
19. Multidimensional Array - CS1010 Programming Methodology
The example below allocate memory for a 2D array that is shaped like a half-square: the first row has one element, second row two elements, third row three, and so on. double *half_square[10]; for (long i = 0; i < 10; i += 1) { half_square[i] = calloc(i+1, sizeof(double)); }
Top answer
1 of 4
9

Are the first two ways of defining the array equivalent in memory?

Not quite. In the second type they are almost certainly contiguous, while in the first type this is not sure.

Type 1: in-memory representation will look like this:

          +---+---+---+---+---+---+---+---+---+---+
    double| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |   
          +---+---+---+---+---+---+---+---+---+---+ 
            ^
            |------------------------------------                                     
                .   .   .   .   .   .   .   .   |    // ten rows of doubles
                                                -
          +---+---+---+---+---+---+---+---+---+--|+
    double| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0||   
          +---+---+---+---+---+---+---+---+---+--|+
            ^   .   .   .                       -
            |   ^   ^   ^   .   .   .   .   .   |
            |   |   |   |   ^   ^   ^   ^   ^   |
          +-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+
array1[ii]| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | // each cell points to ten doubles
          +---+---+---+---+---+---+---+---+---+---+
            ^
            |
            |
          +-|-+
    array1| | |
          +---+

Type 2: in-memory representation will look like this:

          +---+---+---+---+---+---+---+---+---+---+     +---+
    double| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 |  
          +---+---+---+---+---+---+---+---+---+---+     +---+
            ^   ^   ^   ^   ^   ^   ^   ^   ^   ^         ^
            |   |   |   |   |   |   |   |   |   |         |
            |   |   |   |   |   |   |   |   |   |         |
          +-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+-|-+     +-|-+
array1[ii]| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... |99 | // each cell points to one double
          +---+---+---+---+---+---+---+---+---+---+     +---+
            ^
            |
            |
          +-|-+
    array1| | |
          +---+
2 of 4
1

Simple Example

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

int **d ;
int sum();

//----------------------------------------------  
int main(){

    d = (int **)calloc(3,sizeof(int*));
    printf("\n%d",sum());     
}

//-----------------------------------------------
int sum(){
   int s = 0;
   for(int i = 0; i < 3; i++)
       d[i] = (int *) calloc (3,sizeof(int));

   for(int i = 0; i < 3; i++){ 
       for(int j = 0; j < 3; j++){
           d[i][j] = i+j;
           s += d[i][j];
           printf("\n array[%d][%d]-> %d",i,j,d[i][j]);
        }
   }
   return s;
}
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 47887-calloc-2-d-array-creation.html
CALLOC / 2-D Array Creation
December 2, 2003 - #include <stdio.h> #include <stdlib.h> int main ( void ) { int i, j; int row, col; int **array; printf ( "Enter dimensions (row,col): " ); fflush ( stdout ); if ( scanf ( "%d%*c%d", &row, &col ) != 2 ) { fprintf ( stderr, "Some kind of input problem\n" ); return EXIT_FAILURE; } /* * No error checking, it hides the logic */ array = calloc ( row, sizeof *array ); for ( i = 0; i < row; i++ ) array[i] = calloc ( col, sizeof *array[i] ); for ( i = 0; i < row; i++ ) { for ( j = 0; j < col; j++ ) array[i][j] = i * j; } for ( i = 0; i < row; i++ ) { for ( j = 0; j < col; j++ ) printf ( "%-5d", array[i][j] ); printf ( "\n" ); } for ( i = 0; i < row; i++ ) free ( array[i] ); free ( array ); return EXIT_SUCCESS; }
🌐
Reddit
reddit.com › r/c_programming › malloc() question for 2d array
r/C_Programming on Reddit: malloc() question for 2d array
November 8, 2020 -

I am confused as to how and what malloc() is exactly doing/making with my specific line.

I am trying to allocate for a game board.

I have the lines:

char *board;
int length = 7;
int height = 6;
board = (char*)malloc(length * height * sizeof(char));

printf("%lu\n", sizeof(board));  //to test the size of my board

The board results as having a size of 8, which confuses me because I am intending it to have a size of 42 (7 * 6 = 42). I think I remember reading somewhere that for 2d arrays in C, the coordinates of an index are interpreted as if it were a 1d array. So a row of 7, col of 6 would just go to a size of 42 (or something of the sort? I feel I have something wrong about this).

For comparison, the code:

char board[7][6]
printf("%lu", sizeof(board));

gives me a resulting board size of 42 as expected.

So can anyone explain to me what it is I am doing wrong with malloc? What is the difference between the two ways I am creating a 2d array board, one being through malloc, the other through the statement char board[7][6]; ?

Find elsewhere
Top answer
1 of 2
3

This

int **      numberOfConstPiArray = calloc(invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int *));

is not an allocation of a two-dimensional array because at least the type of numberOfConstPiArray is int ** instead of for example int ( * )[kernelColumnCount].

If your compiler supports variable length arrays then you could use the following approach as it is shown in the demonstrative program

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

int main(void) 
{
    size_t n = 5;

    int ( *a )[n] = calloc( n * n, sizeof( int ) );

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n; j++ ) a[i][j] = i * n + j;           
    }

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n; j++ ) printf( "%2d ", a[i][j] );
        putchar( '\n' );
    }

    free( a );

    return 0;
}

The program output is

 0  1  2  3  4 
 5  6  7  8  9 
10 11 12 13 14 
15 16 17 18 19 
20 21 22 23 24 

Or you can allocate an array of arrays the following way.

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

int main(void) 
{
    size_t n = 5;

    int **a = calloc( n, sizeof( int * ) );

    for ( size_t i = 0; i < n; i++ )
    {
        a[i] = calloc( n, sizeof( int ) );
    }

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n; j++ ) a[i][j] = i * n + j;           
    }

    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n; j++ ) printf( "%2d ", a[i][j] );
        putchar( '\n' );
    }

    for ( size_t i = 0; i < n; i++ )
    {
        free( a[i] );
    }

    free( a );

    return 0;
}

The program output is the same as shown above.

2 of 2
1
numberOfConstPiArray[countKernel][col]

is getting an int* from numberOfConstPiArray[countKernel], then trying to dereference col'th element of this int*, and fails, as numberOfConstPiArray[countKernel] was not initialized with an reference to int array memory.

You may use instead:

int *      numberOfConstPiArray = calloc(invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int));
memset(numberOfConstPiArray, 0, invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int));

...
        numberOfConstPiArray[countKernel * kernelColumnCount + col] = 1;
🌐
Medium
medium.com › @MarkAiCode › dynamic-2d-array-allocation-in-c-2745e65d9828
Dynamic 2D Array Allocation in C. Memory management in C can be tricky… | by Mark Ai Code | Medium
October 27, 2024 - Before diving into 2D arrays, let’s quickly refresh the fundamentals of dynamic memory allocation: malloc(): Allocates a block of uninitialized memory · calloc(): Allocates and initializes memory to zero
🌐
Vaia
vaia.com › dynamic allocation of array in c
Dynamic Allocation of Array in C: Techniques & Examples - Vaia
To dynamically allocate memory for a multi-dimensional array in C, use `malloc()` or `calloc()`. First, allocate memory for an array of pointers, and then for each pointer, allocate an array of elements. For example, for a 2D array, allocate rows first, then columns for each row pointer.
🌐
Reddit
reddit.com › r/cs50 › week 4, dynamic memory allocation (calloc) question
r/cs50 on Reddit: Week 4, Dynamic Memory Allocation (calloc) question
January 13, 2025 -

So I'm reading the code from the filter problem and having a hard time visualizing this line.

According to the documentation for calloc, it's *calloc(n, element-size);

So the left side is basically saying "create a pointer called image, that points to an array of length [width], and the element in the array is of type RBGTRIPLE. This is a single 1D array with length [width].

On the right-hand side, calloc is allocating enough memory for the entire image.

I struggle to see how a 1D array somehow turns into a 2D array?

does calloc() only gives the amount of memory, not define the structure of the memory?

why isn't the left side coded like this "RBGTRIPLE(*image)[height][width]" ?

it initiates an array of length[width], but then after the calloc, you can index the image as image[row][column]

// Allocate memory for image
    RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));
🌐
GameDev.net
gamedev.net › forums › topic › 324985-calloc-2d-arrays › 324985
calloc 2d arrays - General and Gameplay Programming - GameDev.net
June 10, 2005 - However, if you really must, here is a basic example of a 2D array. No error checking, which I do recommend you include in your own implementation. (Been awhile since I've actually played with C, spot me if there's any errors.) #include <cstdio>#include <cstdlib>#include <ctime>int main() { srand(time(0)); int** dArray = (int**)calloc(sizeof(int*) * 10, sizeof(int*)); for (int n = 0; n < 10; ++n) dArray[n] = (int*)calloc(sizeof(int) * 10, sizeof(int)); for (int y = 0; y < 10; ++y) for (int x = 0; x < 10; ++x) dArray[y][x] = rand() % 256; printf("%d %d\n", dArray[0][5], dArray[5][0]); for (int n = 0; n < 10; ++n) free(dArray[n]); free(dArray); return 0;}
🌐
Quora
quora.com › How-do-you-allocate-memory-for-a-two-dimensional-array-using-malloc-in-C
How to allocate memory for a two-dimensional array using malloc() in C++ - Quora
Answer (1 of 3): To allocate memory for a two-dimensional array using [code ]malloc()[/code] in C++, you can first allocate memory for an array of pointers, each of which points to a row of the two-dimensional array.
🌐
Aticleworld
aticleworld.com › home › how to dynamically allocate a 1d and 2d array in c.
How to dynamically allocate a 1D and 2D array in c. - Aticleworld
August 18, 2021 - The advantage of a dynamically allocated array is that it is allocated on the heap at runtime. The C language provides a library function to request for the heap memory at runtime. In the below program, I am using malloc to allocate the dynamic memory for the 1D and 2D array.
🌐
Stack Overflow
stackoverflow.com › questions › 55356135 › how-to-use-2d-calloced-arrays-in-functions-in-c
How to use 2D calloced arrays in functions in C? - Stack Overflow
Unless, matrix pointer artimethic is also an issue :-) ... int (*p)[rows][cols] = malloc(sizeof *p) will allocate memory for a 2D array, yet with int **matrix, it appears you want something else.
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › arrays.html
2.5.1. Single-Dimensional Arrays
Like 1D dynamically allocated arrays, the pointer variable for a 2D array is allocated on the stack. That pointer is then assigned the value returned by the call to malloc, which represents the base address of the contiguous chunk of NxM int storage locations in the heap memory. Because this method uses a single chunk of malloc’ed space for the 2D array, the memory allocation is as efficient as possible (it only requires one call to malloc for the entire 2D array).
🌐
Equestionanswers
equestionanswers.com › c › dynamic-2d-3d-array.php
Dynamic 2D 3D array in c | Malloc del input printing 2D 3D
Like take a integer pointer and call malloc/calloc with the proper memory size in bytes. ... Leter we can use this array variable in the same way as we use static array elements. Each elements can be accessed by operator[] like array[index]. Thus it is easy to convert a program written with ...
🌐
CopyProgramming
copyprogramming.com › howto › calloc-a-two-dimensional-array
Arrays: Creating a Two-Dimensional Array using Calloc
April 30, 2023 - Currently, my method for creating a 2D array involves the following steps. int * own; own = (int *)calloc(mem_size, sizeof(int)); for (i=0;i