操纵2d数组时出现“不可见”错误。 (0个错误,0个警告)

时间:2013-04-11 21:20:18

标签: c arrays malloc transpose

应用程序崩溃,但我看不出原因。 我已多次检查代码,但仍有问题。

我有2d数组'a'(NxM),我必须转置它。新数组是'p'(MxN)。

以下是计划的一部分:

/// 7: Transposing array. ( NxM ---> MxN ).   
int **p = NULL;

p = (int **)malloc(M*sizeof(int *));

if ( NULL == p)
{
    printf("Failed to allocate memory.");
    return 1;
}

for ( i = 0; i < M; i++ )
    p[i] = (int *)malloc(N*sizeof(int ));

// Filling in the new array called "p" with '0's.
for ( i = 0; i < M; i++ )
    for ( j = 0; j < N; j++ )
        p[i][j] = 0;

// Transposing array.
for ( i = 0; i < N; i++ )
{
    for ( j = 0; j < M; j++ )
    {
        a[i][j] = p[j][i];
    }
}

// Displaying ARRAY
printf(">>>\n\n");
for ( i = 0; i < M; i++ )
{
    for ( j = 0; j < N; j++ )
        printf("%4d ", p[i][j]);
    printf("\n");
}

请告诉我有什么问题。

更新:我为我犯的错误道歉..

// Filling in the new array called "p" with '0's.
for ( i = 0; i < M; i++ )
    for ( j = 0; j < N; j++ )
        p[i][j] = 0;   // there will be 'p', not 'a'.

2 个答案:

答案 0 :(得分:1)

由于a的大小为N x M,因此问题来自此循环,您正在访问M x N个元素,而不是N x M

// Filling in the new array called "p" with '0's.
for ( i = 0; i < M; i++ )
    for ( j = 0; j < N; j++ )
        a[i][j] = 0;

这个循环应该是

for ( i = 0; i < N; i++ ) // M is swapped with N
    for ( j = 0; j < M; j++ ) // N is swapped with M
        a[i][j] = 0;

而且,根据您的问题,a是需要转换为p的输入数组。因此,处理步骤应该是

// Transposing array.
for ( i = 0; i < N; i++ )
{ 
    for ( j = 0; j < M; j++ )
    {
        p[j][i] = a[i][j];
    }
}

通过这些更改,代码按预期工作。在不同阶段打印数据的示例代码将在http://cfiddle.net/zoZazB

上传

答案 1 :(得分:0)

问题出在此处:a属于N *M,但您意外地将其M*N

 // Filling in the new array called "p" with '0's.
 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^You are doing with a not p below
 for ( i = 0; i < M; i++ )
    for ( j = 0; j < N; j++ )
         a[i][j] = 0;
 //here it seems that a is of M*N not N*M
 //your comment and code does not match

大小不匹配会导致您访问不属于a的内存,因此会崩溃。