[英]Allocating a 2D array using calloc
我试图使用calloc动态分配2D数组。
这是我尝试过的代码。
int ** numberOfConstPiArray = calloc(invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int *));
我已经初始化了如下所示的变量
int numberOfUniqueKernels = 100;
int kernelColumnCount = 10;
int dimensionalMatrixColumnCount = 10;
以下是循环并尝试更改2D数组的主要代码。
for (int countKernel = 0; countKernel < numberOfUniqueKernels; countKernel++)
{
int countNumberOfConst = 0;
int numberOfTerms = 0;
int numberOfConstPi = 0;
for (int col = 0; col < kernelColumnCount; col++)
{
for (int row = 0; row < dimensionalMatrixColumnCount; row++)
{
if (some condition is satisfied)
{
countNumberOfConst += 1;
}
if (another condition satisfied)
{
numberOfTerms += 1;
}
}
if(countNumberOfConst == numberOfTerms)
{
numberOfConstPi += 1;
numberOfConstPiArray[countKernel][col] = 1;
}
countNumberOfConst=0;
numberOfTerms=0;
}
}
这似乎不起作用。 我理解似乎没有工作是模糊的,但由于此代码是大型编译器的一部分,因此我无法打印出特定的输出。 为此道歉。
我的问题是:我是否以正确的方式初始化了数组,并且修改了数组中元素的值是正确的。
谢谢。
这个
int ** numberOfConstPiArray = calloc(invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int *));
不是二维数组的分配,因为至少numberOfConstPiArray
的类型是int **
而不是例如int ( * )[kernelColumnCount]
。
如果您的编译器支持可变长度数组,那么您可以使用以下方法,如演示程序中所示
#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;
}
程序输出是
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
或者您可以通过以下方式分配数组数组。
#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;
}
程序输出与上面显示的相同。
numberOfConstPiArray[countKernel][col]
越来越一个int*
从numberOfConstPiArray[countKernel]
然后试图解除引用col
“日本的元素int*
,和发生故障,如numberOfConstPiArray[countKernel]
不与一个参考初始化为int
阵列存储器。
您可以改用:
int * numberOfConstPiArray = calloc(invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int));
memset(numberOfConstPiArray, 0, invariannumberOfUniqueKernels * kernelColumnCount, sizeof(int));
...
numberOfConstPiArray[countKernel * kernelColumnCount + col] = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.