![](/img/trans.png)
[英]Why we have to pass the values instead of the address into a “call by reference” function in C++?
[英]Why I get address instead of values , in C++ code?
我的代码从* .mtx文件中读取了一个稀疏矩阵,并且应该在控制台上打印该矩阵(仅用于测试,对于实际情况,我想返回稀疏矩阵),但是他打印的是地址而不是值。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
struct MatriceRara
{
int *Linie, *Coloana, *Valoare;
int nrElemente, nrLinii, nrColoane;
};
MatriceRara Read(const char* mtx) {
const char * mtx_file = mtx;
ifstream fin(mtx_file);
MatriceRara matR;
int nrElemente, nrLinii, nrColoane;
// skip header:
while (fin.peek() == '%') fin.ignore(2048, '\n');
// read parameters:
fin >> nrLinii >> nrColoane >> nrElemente;
matR.nrElemente = nrElemente;
matR.nrLinii = nrLinii;
matR.nrColoane = nrColoane;
cout << "Number of rows: " << matR.nrLinii <<endl;
cout << "Number of columns: " << matR.nrColoane << endl;
cout << "Number of not null values: " << matR.nrElemente << endl;
for (int i = 0; i< nrElemente; i++)
{
int *m ,*n,*data;
fin >> (int &) m >> (int &) n >> (int &) data;
matR.Linie = m;
matR.Coloana = n;
matR.Valoare = data;
//only for test:
cout<<matR.Linie << " " << matR.Coloana << " " << matR.Valoare <<endl;
}
//return matR;
}
int main () {
MatriceRara a = Read("Amica.mtx");
}
我的输出:
Number of rows: 5
Number of columns: 5
Number of not null values: 8
0x7fff00000001 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
0x7fff00000000 0x7f4400000001 0x1
因此,正如您在我的输出中看到的那样,它打印的是地址,而不是值。 非常感谢 !
您声明了以下成员作为int的指针:
int *Linie, *Coloana, *Valoare;
然后打印这些指针:
cout<<matR.Linie << " " << matR.Coloana << " " << matR.Valoare <<endl;
因此,您得到的是:指针的值(例如地址)
因为变量Linie
, Coloana
和Valoare
是指针。
您必须在*
之前取消引用指针。
int value;
value = *m;
如果要打印这些值,请再次在这里:
cout<< *matR.Linie << " " << *matR.Coloana << " " << *matR.Valoare << endl;
您所有类型为int *
变量和类成员实际上都应该为int
类型。 当前它们是未初始化的指针,而实际上它们实际上是整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.