【发布时间】:2011-05-24 02:23:57
【问题描述】:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void multiplier_matrice_vecteur (char * v0, char * A, int N)
{
int i,j,k;
char somme;
for (i = 0; i < N; i++) //On fait N calculs car c'est une matrice 1xN
{
//On fait N additions + multiplications
somme = 0;
for (j = 0; j < N; j++)
{
somme += v0[i] * A[i * N + j];
}
v0[i] = somme;
}
}
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 N;
char *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);
N = nbr1;
matrice = new char(nbr1 * nbr1); //Memoire dynamique pour la matrice dadjacence n x n
memset(matrice, 0, nbr1*nbr1);
premiereLignefaite = true;
continue;
}
//On construit notre matrice d'adjacence
sscanf(ligne, "%d %d", &nbr1, &nbr2);
matrice[nbr1 * N + nbr2 ] = 1;
}
printf("Matrice d'adjacence %dx%d : \n", N, N);
//Affichage de la matrice d'adjacence
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%c ", matrice[i * N + j] + '0');
}
printf("\n");
}
//Application de l'algo étapes par étapes
double tolerance = 0.00001; //Niveau de tolérance de la méthode
char * v0; //vecteur propre taille N
char * v; //vecteur tampon
int valeur; //valeur propre
int valeur_tamp; //valeur propre tampon
//Initialiser v0
v0 = new char(N);
memset(v0, 1, N);
//Initialiser A (déja fait)
//Initialiser tolérance (deja fait)
valeur = 0;
while (1)
{
valeur_tamp = valeur;
//Multiplication du vecteur par la matrice
multiplier_matrice_vecteur(v0, matrice, N);
}
//Désallocation de la mémoire
delete matrice;
//Fermeture des fichiers etc
fclose(graphe);
fclose(resultat);
return 0;
}
这是我从下午 2 点开始在笔记本电脑上编写的程序。我正在使用 Visual Studio 2008 和 Windows 7 64 位。我正在编码,一切顺利。当我尝试测试我的程序时,该行:
v0 = new char(N);
给我一个例外。我尝试使用 malloc 和 calloc 来获取记忆,我会得到什么?一个空指针!!我的机器上有 4 gigs 的 ram,我不可能在这里获得 9 字节的内存。我完全不明白这一点。
对于那些拥有 Visual Studio 2008 并希望在相同环境下进行测试的人,您将需要文件 graphe.txt,这是该文件:
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
我以为这是机器问题,所以我回到家,我在台式电脑上尝试了该程序,但还是同样的问题......
我必须尝试使用 GCC,但由于我一直在使用 Visual C++,所以我想解决这个环境中的问题...
编辑:下面的代码现在可以工作了。出于某种原因,如果你在第一个 new 中使用括号,它会起作用,但下次你使用 new 时,它就不起作用了!! 如果我将两个新分配都使用 [] 语法,它就可以工作。如果我将第一个新分配与 [] 和第二个与 (),它也可以工作。诡异的。无论如何,从现在开始我将使用 []...谢谢大家。
【问题讨论】:
-
如果
N控制到达该行但异常的值是多少? -
您确定这里没有异常吗?
memset(v0, 1, N); -
不,它发生在尝试在这里执行 memset 之前。
-
括号分配单个字符并将值初始化为N。方括号分配一个字符数组。
标签: c++ visual-c++ memory-management