[英]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.