我的程序运行良好,但不返回 0

问题描述 投票:0回答:1
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>

int i,j;

void display_matrix(int matrix[],int rows,int colombs){
    for(i=0;i<rows;i++){
     for(j=0;j<colombs;j++)
        printf("%5d ",matrix[i*rows+j]);
    printf("\n");
    }
}

int *create_matrix(int rows,int colombs,int min,int max){
    int *matrix=NULL;
    matrix=(int*)calloc(colombs*rows,sizeof(int));
    for(i=0;i<rows;i++)
        for(j=0;j<colombs;j++)
            matrix[i*rows+j]=(rand()%(max-min+1))+min;
    
    return matrix;
}



int main(){
    
    int *m=NULL,row,col;
    
    do{
        printf("Give the number of rows:\n");
        scanf("%d",&row);
    }while(row<=0);
    
    do{
        printf("Give the number of colombs:\n");
        scanf("%d",&col);
    }while(col<=0);
    
    
    m=create_matrix(row,col,10,99);
    display_matrix(m,row,col);

    return 0;
}

矩阵按预期显示,但程序返回值为 3221226356。我尝试更改函数 create_matrix() 中的行和列,返回值为 0,但矩阵有垃圾数据。That is the result after i run the program

c pointers matrix return-value
1个回答
0
投票

您似乎使用的是 Windows。
在 Windows 上,错误代码

3221226356
(十六进制为
0xc0000374
)表示堆损坏。

损坏是由于在无效索引处访问您的

matrix
而引起的。

您的错误在于将行和列索引转换为

matrix
中的索引。

代替:

i*rows+j

应该是:
i*colombs+j

您在 2 个地方遇到此错误:

  1. 打印矩阵时(在
    display_matrix
    中):
    printf("%5d ",matrix[i*rows+j]);
    
  2. 当您填充矩阵时(在
    create_matrix
    中):
    matrix[i*rows+j]=(rand()%(max-min+1))+min;
    

旁注:

colombs
可能应该重命名为
colomns

© www.soinside.com 2019 - 2024. All rights reserved.