2010-12-11 1647 views
2
#include <stdio.h> 
#include <iostream> 

using namespace std; 

    int main(void) 
    { 
bool premiereLignefaite = false; 
//Lire le fichier 
FILE * graphe = fopen("graphe.txt", "r"); 
//Fichier de sortie 
FILE * resultat = fopen("resultat.txt", "w"); 
int nbr1, nbr2; 
int *matrice; //pointeur vers la matrice d'adjacence 

//Ligne lue 
static char ligne[50]; 

while (fgets(ligne, 50, graphe) != NULL) //retourne 0 quand on a end-of-file 
{ 
    //La premiere ligne est différente 
    if (premiereLignefaite == false) { 
     //Initialiser une matrice d'adjacence NxN 
     sscanf(ligne, "%d %d", &nbr1, &nbr2); 
     matrice = new int(nbr1 * nbr1); //Memoire dynamique pour la matrice dadjacence n x n 
     premiereLignefaite = true; 
     continue; 
    } 
    //On construit notre matrice d'adjacence 
    sscanf(ligne, "%d %d", &nbr1, &nbr2); 
    matrice[nbr1][nbr2] = 1; 
} 

int u = 2+2; 


return 0; 
} 

所以我在这条线得到一个错误: 矩阵的计算[NBR1] [NBR2] = 1; 我只是试图从文本文件建立一个邻接列表。我不明白我做错了什么。谢谢。错误C2109:下标要求数组或指针类型

编辑:由于人们询问它,这是我的图形文件。第一行是顶点的数量和边的数量(不是有用的imo) 以下几行是我的边,我使用第一行为NxN图分配内存,下面几行填充我的邻接矩阵。

9 20 
0 1 
0 2 
1 0 
1 2 
1 3 
1 5 
2 0 
2 1 
2 3 
3 1 
3 2 
3 4 
4 3 
5 1 
5 6 
5 7 
6 5 
6 8 
7 5 
8 6 

回答

2

int *matrice;意味着矩阵的计算是一个指向一个int(或整数),所以matrice[a]会给你一个int。指针没有关于数组维度的任何信息,所以你不能进行二维访问。

你想要做你的存储阵列的尺寸,然后做

matrice[nbr1 * numberOfColumns + nbr2] = 1; 

旁注:如果你不小心界通过指针

  • 原始数组访问是非常危险的检查。考虑std :: vector <>。
  • 你可能是指new int[nbr1 * nbr2]
+0

我不需要添加* sizeof(int),因为C++会自动对它进行调整吗? – toto 2010-12-11 22:58:07

+0

我得到了我的矩阵与您的技术。对于多维动态数组,不能使用[] []语法太糟糕了!我真的希望我能做到这一点。 – toto 2010-12-11 23:00:57

+0

很高兴听到它的工作!要回答你的问题 - 是的,新会自动分配sizeof(type)乘以元素的数量。如果你使用C的'malloc()',你将不得不使用sizeof()。 – EboMike 2010-12-12 17:58:34

1

matrice宣告为int *这使它成为一个signle维数组。它不能作为多维数组访问matrice[nbr1][nbr2]。同时检查你的内存分配代码。它应该是new int[nbr1 * nbr2],而不是new int(nbr1 * nbr2)

1

matrice[x]*(matrice+x)相同,matrice[x][y]*(*(matrice+x)+y)相同。

所以问题是,当你写matrice[nbr1][nbr2],这就像写作*(*(matrice+nbr1)+nbr2)一样。由于matrice只是一个指针,而不是指向指针的指针,所以这当然不起作用。

+0

感谢您的解释! – toto 2010-12-11 22:59:04

相关问题