0

App crashes but I can't see the reason. I've been examining the code for many times, but still there is a problem.

I have 2d array 'a'(NxM) and I have to transpose it. The new array is 'p'(MxN).

Here is part of program:

/// 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");
}

Tell me what is wrong, please.

UPDATE: I apologize for the mistake I've made..

// 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'.
4

2 回答 2

1

由于a是 size 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上传了在不同阶段打印数据的示例代码

于 2013-04-11T21:23:52.973 回答
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,因此崩溃。

于 2013-04-11T21:24:30.327 回答