首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手,动态数组申请

2013-12-28 
新手求助,动态数组申请 typedef struct Matrix{int heightint widthfloat*element}Matrixint main(){.

新手求助,动态数组申请
 


typedef struct Matrix{
int height;
int width;
float*element;
}Matrix;
int main(){.......

;
cout<<"输入A矩阵的行数"
<<endl;
cin>>A.height;
cout<<"输入A矩阵的宽度"
<<endl;
cin>>A.width;
if((A.element=new float[A.height*A.width])==NULL){
cout<<"不能分配"<<endl;
return(1);
}
init(&A);
B.height=A.width;
cout<<"输入B矩阵的宽度"
<<endl;
cin>>B.width;
if((B.element=new float[B.height*B.width])==NULL){
cout<<"不能分配"<<endl;
return(1);
}



第一个数组可以申请,第二个数组申请的时候会显示.exe触发一个断点,可能是堆损坏,是不是只能申请一个动态数组?该怎么解决,初学编程,求指导
[解决办法]
可能是init(&A)的问题。

引用:
 

typedef struct Matrix{
int height;
int width;
float*element;
}Matrix;
int main(){.......

;
cout<<"输入A矩阵的行数"
<<endl;
cin>>A.height;
cout<<"输入A矩阵的宽度"
<<endl;
cin>>A.width;
if((A.element=new float[A.height*A.width])==NULL){
cout<<"不能分配"<<endl;
return(1);
}
init(&A);
B.height=A.width;
cout<<"输入B矩阵的宽度"
<<endl;
cin>>B.width;
if((B.element=new float[B.height*B.width])==NULL){
cout<<"不能分配"<<endl;
return(1);
}



第一个数组可以申请,第二个数组申请的时候会显示.exe触发一个断点,可能是堆损坏,是不是只能申请一个动态数组?该怎么解决,初学编程,求指导

[解决办法]
最好把代码贴全~~~,有可能不是你贴出来的代码引起的问题。
[解决办法]
调试过了是吧??
[解决办法]
new之前看下里边的大小是不是有问题
[解决办法]
//在堆中开辟一个4×5的二维int数组
#include <stdio.h>
#include <malloc.h>
int **p;
int i,j;
void main() {
    p=(int **)malloc(4*sizeof(int *));
    if (NULL==p) return;
    for (i=0;i<4;i++) {
        p[i]=(int *)malloc(5*sizeof(int));
        if (NULL==p[i]) return;
    }
    for (i=0;i<4;i++) {
        for (j=0;j<5;j++) {
            p[i][j]=i*5+j;
        }
    }
    for (i=0;i<4;i++) {
        for (j=0;j<5;j++) {
            printf(" %2d",p[i][j]);
        }
        printf("\n");
    }
    for (i=0;i<4;i++) {
        free(p[i]);
    }
    free(p);
}
//  0  1  2  3  4
//  5  6  7  8  9
// 10 11 12 13 14
// 15 16 17 18 19

[解决办法]
一下代码编译运行没有出问题。

# include <iostream>

using namespace std;

struct Matrix {
    int height;
    int width;
    float * element;
};

int main()
{
    Matrix A, B;
    cout << "input A's height" << endl;
    cin >> A.height;
    cout << "input A's width" << endl;
    cin >> A.width;
    A.element = new float[A.height * A.width];
    // init(&A);
    B.height = A.width;
    cout << "input B's width" << endl;
    cin >> B.width;
    B.element = new float[B.height * B.width];



    return 0;
}


几个问题要注意下:
1、
这是C++,
typedef struct Matrix {
  int height;
  int width;
  float*element;
} Matrix;
是不必要的,
struct Matrix {};
就可以了

就算在C中LZ的typedef也会引起模糊。

2、
单纯调用new是会抛异常的,所以检查返回值就没意义了(因为要么就成功,返回一定不是NULL,要么就失败抛异常,也轮不到if来检查返回值了)

3、
init(&A);被我注释掉了,个人认为这里容易出错。

[解决办法]
把B.height*B.width打印出来

热点排行