-4
我的任务是替换对角线矩阵上的向量元素和元素。矢量由用户输入并且矩阵是随机的。例如,我写的矢量:使用malloc和指针替换矩阵中的向量
1 2 3
和随机矩阵是
7 0 0
0 3 0
0 0 8
我一定要得到这个
1) 7 3 8
2)
1 0 0
0 2 0
0 0 3
它的第一部分我得到了,但第二个我” m堆叠。这里是进入向量:
int size;
std::cout << ("Enter the dimentoinal of vector and matrix (enter one number): ");
std::cin >> size;
int * arrayPtr = (int*) calloc(size,sizeof(int));
if (arrayPtr == NULL) exit (1);
for (int ix = 0; ix < size; ix++)
{
std::cout << "Enter element #" << ix<< " ";
std::cin >> arrayPtr[ix];
}
system ("clear") ;
std::cout << "\n\nResulting vector is:\n[ ";
for (int ix = 0; ix < size; ix++)
{
std::cout << arrayPtr[ix] << " ";
}
cout << "]\n\n\n" ;
这里是代码,完全不工作(在屏幕上是不正确的结果):
cout << "The new matrix is :\n" ;
int * matr_n = (int*) calloc(size,sizeof(int));
cout << "\n" ;
for (int ix = 0 ; ix<size; ix++)
{
matr_n = &arrayPtr[ix] ;
cout << *matr_n << " " ;
for (int i = 0; i<size; i++)
{
cout << "\n" ;
for (int j = 0; j<size; j++)
{
if (i==j)
{
cout << *matr_n << " " ;
}
else
cout << 0 << " " ;
}
}
}
我知道问题出在使用指针或的malloc /释放calloc功能,但初学者很难赶上它。 你能解决它吗?
** **缩进你为基督的缘故代码。 – gsamaras
*为什么*你想在C++中使用'malloc'?这几乎总是一个坏主意 – UnholySheep
*“你可以修复它,请吗?” - 使用'std :: vector'。 –