【发布时间】:2021-04-07 11:37:52
【问题描述】:
在为一个 CS 类项目实现图表时,我声明了这两个结构
typedef struct person {
char name[128];
int age;
} Person;
typedef struct graph {
int knots;
int adjacencies[500][500];
Person personList[500];
} Graph;
void insertPerson(Graph *g, Person p) {
g->personList[knots] = p;
(g->knots)++;
}
void writeAdjacencies(Graph g) {
for(int i = 0; i < MAXDIM; i++) {
for(int j = 0; j < MAXDIM; j++) {
printf("%d ", g.adjacencies[i][j]);
}
printf("\n");
}
}
一切都很好,除了在尝试创建菜单功能(读取输入然后决定是添加新人还是删除现有人等)时,传递一个图形指针然后使用它的指向实例似乎正在生成分段错误。
void checkInput(int input, Graph *g) {
int temp;
char tempName[128];
if(input == 1 ) {
printf("\n Name: ");
scanf(" %[^\n]", tempName);
printf("%s\n", tempName);
Person p;
strcpy(p.name, tempName);
/* takes graph pointer a person and just adds person to personList and increases knots
it's working as intended
*/
insertPerson(g, p);
/* Goes through each element in the matrix and prints it
this is the one causing problems
*/
writeAdjacencies(*g);
}
}
在我将 *g 作为参数传递之前,代码工作正常 - 也就是说,如果我将 writeAdjacencies(*g) 放在注释下,它不会造成任何问题。
我不明白这里有什么问题?我觉得好像我在使用指针,就像我全年所做的那样,它奏效了。也许我可以传递一个空指针?但我确实在我认为的 main 函数中初始化了它。
main.c:
Graph graph;
for(int i = 0; i < MAXDIM; i++) {
for(int j = 0; j < MAXDIM; j++) {
g.adjacencies[i][j] = 0;
}
}
g.knots = 0;
checkInput(0, &g);
欢迎任何帮助!
编辑:包括两个缺失的功能
【问题讨论】:
-
这不是一个最小的可重现示例。请edit您的问题,提供两个缺失函数的定义,
-
您的
main函数(就您已将其传达给我们而言)引用了变量g但未声明它。请提供minimal reproducible example(如果您还没有这样做,请阅读该链接——这将使您在 Stack Overflow 上的体验更加愉快)。 -
没看过。完成。