【发布时间】:2016-11-25 15:14:23
【问题描述】:
我正在尝试在 C 中实现一个链表,目的是对其进行 BFS。 列表的输入应如下所示:
a-bc
b-a
c-a
表示一个如下所示的列表:
a
/ \
b c
现在,我的问题是我无法读取在 Vertex 结构中定义的变量 name。我的程序因访问读取冲突而出现段错误。虽然printf("%s", s) 采用char *,但将name 转换为char* 并没有帮助。甚至在访问字符之前发生错误?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Vertex Vertex;
typedef struct Vertex
{
char name;
int visited;
int distance;
Vertex* next;
} Vertex;
struct Vertex* AddVertex(Vertex* head, char newVertexName)
{
Vertex* newHead = malloc(sizeof(Vertex));
newHead->name = newVertexName;
printf("added vertex named: %s", newHead->name); // causing the error
newHead->next = head;
newHead->visited = 0;
newHead->distance = 0;
return newHead;
}
int main()
{
// BFS
char s[100];
int l = 0;
const int nNrOfVerts = 27;
Vertex* adjList[28];
// initialise array of pointers
for(int i = 0; i <= nNrOfVerts; ++i)
{
adjList[i] = NULL;
}
// fill vertices with user data
for(int i = 1; i <= nNrOfVerts; ++i)
{
printf("enter %d vert: ", i);
if(scanf("%s", &s) != 1)
{
break;
}
l = strlen(s);
if(l > 2)
{
for(int k = 0; k < l; ++k)
{
// increment to accustom for the - seperator
if(1 == k)
{
k = 2;
}
adjList[i] = AddVertex(adjList[i], s[k]);
}
}
for(int k = 0; k < 100; ++k)
{
s[k] = NULL;
}
}
bfs(adjList);
// printing the list
for(int i = 1; i <= l; ++i)
{
for(int j = 0; j <= nNrOfVerts; ++j)
{
if(adjList[j]->distance == i)
{
printf("Level: %d is: %s", i, adjList[j]->name);
}
printf("No node for dist: %d", i);
}
}
return 0;
}
为此,我如何访问 newHead->name 或 adjList[i]->name 的值?有趣的是,如果我尝试访问 adjList[i]->distance 会返回正确的整数...
【问题讨论】:
-
使用
%c而不是%s。 -
你应该先检查警告。您的代码中有很多问题。你声明了 char s[100] 和 scanf("%s",&s).. 你会得到什么?你定义 s[k]=NULL,... 你怎么能做到?在提问之前,请检查警告。
标签: c struct linked-list