2

我想得到你的帮助来理解和完成我的程序。

这是我必须做的:

“您必须执行以下程序:首先。一个吸收二维整数 arr [M] [N]。M - 行数 N - 列数。(从用户那里收到矩阵大小)二。程序使用辅助函数“shift”将矩阵的值右移一位,如图(输入2代替1,输入3代替2,输入4代替3,... 20代替19,第1位20 ). Shift 必须编写一个函数并在示例矩阵循环中调用她 3 次.."

示例图片: 在此处输入图像描述

错误信息: 在此处输入图像描述

在尝试解决我放弃的问题后,我希望得到您的帮助,以了解我的代码中有什么问题。和记忆有关吗?这是我的代码:

#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "malloc.h"

void shift (int **arr,int rows,int cols);
void freemalloc ( int **arr,int rows);

void main()
{
    int **arr,cols,rows;
    int i,j;
    printf("please insert rows and columns of the matrix: ");
    scanf_s("%d%d",&rows,&cols);
    arr=(int **)malloc(rows*sizeof(int *));
    for(i=0; i<rows; i++)
        arr[i]=(int *)malloc(cols*sizeof(int));
    for (i=0; i<rows; i++)
        for (j=0; j<cols; j++)
        {
            printf("rows %d , cols %d :\n", i, j);
            scanf_s("%d", &arr[i][j]);
        }
    shift (arr,rows,cols);
    freemalloc (arr,rows);
    system("pause");
    return ;
}

void shift (int **arr,int rows,int cols)
{
    int i,j,temp=0;
    for(i=0; i<rows ; i++ )
        for( j=0 ; j<cols ; j++);
    {
        temp=arr[i][j];
        arr[i][j]=arr[i][cols-1];
        arr[i][cols-1]=temp;
    }
    for(i=0; i<rows ; i++)
    {
        for(j=0; j<cols ; j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
}

void freemalloc ( int **arr,int rows)
{
    int i;
    for (i=0 ; i<rows ; i++)
    {
        free(arr[i]);
    }
    free(arr);
}
4

2 回答 2

4

我在一般评论中注意到了这一点,我会在这里放大它。这是错误的,并且会导致未定义的行为

for(i=0; i<rows ; i++ )
    for( j=0 ; j<cols ; j++); // <<== this is wrong.
{
    temp=arr[i][j];
    arr[i][j]=arr[i][cols-1];
    arr[i][cols-1]=temp;
}

后面的分号是完全错误的。有了它,代码就变成了这样:

// A useless nested for loop that runs `i` to `rows` and `j to `cols`
for(i=0; i<rows ; i++ )
    for( j=0 ; j<cols ; j++);

// Now `i=rows` and `j=cols`. then you do this
temp=arr[i][j];
arr[i][j]=arr[i][cols-1];
arr[i][cols-1]=temp;

您正在访问您不拥有的内存,因为arr只能对[rows-1][cols-1]未定义行为之外的任何内容进行索引。

更正

for(i=0; i<rows ; i++ )
    for( j=0 ; j<cols ; j++) // note: no semi-colon.
    {
        temp=arr[i][j];
        arr[i][j]=arr[i][cols-1];
        arr[i][cols-1]=temp;
    }

通过删除该分号来修复您的代码,并且至少解决了您的那部分问题。我不能谈论其他问题。

最后,使您的编译器警告达到迂腐水平。任何合理的编译器都配置了适当的警告,都会发现这个问题。

于 2013-09-16T16:48:22.087 回答
2

这个错误已经在另一个答案中指出了,但让我再给你一个好建议:不要使用指向指针的指针来表示多维数组。

另外,不要强制转换malloc().

这是你应该做的(应该做的):

int (*mat)[width] = malloc(height * sizeof(*mat));
于 2013-09-16T17:04:28.257 回答