为什么我在C++代码中得到地址而不是值

Why I get address instead of values , in C++ code?

本文关键字:地址 C++ 代码 为什么      更新时间:2023-10-16

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

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

因为变量LinieColoanaValoare是指针。

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

int value;
value = *m;

如果你想打印值,请再次点击此处:

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

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