c语言 - 操作 2D 数组时出现"Invisible"错误。(0 错误, 0 警告)



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

我有一个二维数组'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(">>>nn");
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'.

由于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

问题在这里:因为aN *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的内存,因此,崩溃。

相关内容

  • 没有找到相关文章

最新更新