为什么我在C ++代码中获取地址而不是值?

时间:2016-04-29 12:50:02

标签: c++

我的代码从* .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

因此,正如您在我的输出中所看到的,它打印的是地址,而不是值。 非常感谢!

3 个答案:

答案 0 :(得分:4)

您将以下成员声明为int:

的指针
int *Linie, *Coloana, *Valoare;

然后你打印这些指针:

cout<<matR.Linie << " " << matR.Coloana << " " << matR.Valoare <<endl;

所以你得到你所问的:指针的值(例如地址)

答案 1 :(得分:1)

因为变量LinieColoanaValoare是指针。

您必须在*之前取消引用指针。

int value;
value = *m;

如果你想打印这些值,请再次在这里:

cout<< *matR.Linie << " " << *matR.Coloana << " " << *matR.Valoare << endl;

答案 2 :(得分:-4)

类型int *的所有变量和类成员都应该是int类型。目前它们是未初始化的指针,而它们实际上是整数。