gpt4 book ai didi

C语言,邻接矩阵

转载 作者:行者123 更新时间:2023-11-30 15:56:44 25 4
gpt4 key购买 nike

在您的帮助下,我可以从文本文件(input.txt)中获取输入,其中各行由 city1 city2 距离组成...并将城市名称写入矩阵中而不重复。根据这个矩阵我写了一段代码来将它们的距离添加到邻接矩阵中。但输出看起来很奇怪,我的意思是,它不正确。我想在下面的代码中应该缺少或错误的东西。非常感谢任何一点帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]){
int i=1,j, state=0, k, dist,x=0,y=0;

int** myMat;
char *city1, *city2, **matnames;
FILE* p;
city1 = (char*) malloc(sizeof(char));
city2 = (char*) malloc(sizeof(char));
matnames = (char**) malloc(sizeof(char*));
myMat = (int**) malloc(sizeof(int*)*4);
p = fopen(argv[1],"r");

/************************************************************/
matnames[0] = (char*) malloc(sizeof(char));
matnames[1] = (char*) malloc(sizeof(char));
matnames[2] = (char*) malloc(sizeof(char));
matnames[2] = NULL;
fscanf(p, "%s %s %d", city1, city2, &dist);
strcpy(matnames[0],city1);
strcpy(matnames[1],city2);
/************************************************************/
for(i=0;i<3;i++){
myMat[i] = (int*) malloc(sizeof(int));
}
myMat[1][2] = dist; /* the first two distances placed at matnames */
myMat[2][1] = dist;

/************************************************************/
while( fscanf(p,"%s %s %d",city1,city2, &dist) != EOF){
for(j=0; matnames[j]!=NULL; j++){
if( strcmp(matnames[j], city1) != 0){
state++;
}
}
if(state == j){
matnames = realloc(matnames, sizeof(char*)*(j+3));
matnames[j] = (char*) malloc(sizeof(char));
strcpy(matnames[j], city1);
matnames[j+1] = (char*) malloc(sizeof(char));
matnames[j+1] = NULL;
}
state = 0;
for(j=0; strcmp(matnames[j], city1) != 0;j++){
x++; /* "x" finds the city1 indeks from matnames*/
}

for(k=0; matnames[k] != NULL;k++){
if( strcmp(matnames[k], city2) != 0){
state++;
}
}
if(state == k){
matnames = realloc(matnames, sizeof(char*)*(k+4));
matnames[k] = (char*) malloc(sizeof(char));
matnames[k+1] = (char*) malloc(sizeof(char));
strcpy(matnames[k], city2);
matnames[k+1] = NULL;
}
state = 0;
/* till to here the names of cities are placed in matnames without repetion*/
for(j=0; strcmp(matnames[j], city2) != 0;j++){
y++; /* "y" finds the city2 indeks from matnames*/
}
/****** the problem should be in this part */
myMat = realloc(myMat,sizeof(int*)*(k+3));
for(i=2;i<k+2;i++){
myMat[i] = (int*) malloc(sizeof(int));
}
myMat[x][y] = dist;
myMat[y][x] = dist;
x=0; y=0;
}
return 0;
}

最佳答案

您将 1 个字符分配给 city1 和 city2(使用 sizeof(char) 进行 malloc)。除非您的城市都只有一个字符,否则 fscanf 将超出范围。

使用 city1 = (char*) malloc(1024) 重试,这样城市可以更长一些。

matnames 并不是很明显你想要它是什么,但你分配它 1 sizeof(pointer),即 4 个字节。然后你做 matnames[0] = ..., matnames[1] = ...matnames[1] 已经溢出您分配的内存。所以你是在随机的地方写的。

C 语言对于内存分配非常宽容,但结果是完全不可预测的。确保您的 malloc 空间足够,并尽可能考虑其他语言。 :)

关于C语言,邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com