c - 读取结构中包含的 char 会导致访问冲突异常

标签 c struct linked-list

我正在尝试用 C 语言实现一个链表,目的是对其进行 BFS。 列表的输入应如下所示:

a-bc
b-a
c-a

代表一个如下所示的列表:

 a
/ \
b  c

现在,我的问题是我无法读取在我的 Vertex 结构中定义的变量 name。我的程序出现访问读取冲突的段错误。当 printf("%s", s) 接受一个 char * 时,将 name 转换为 char*没有帮助。甚至在访问 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,则会返回正确的整数...

最佳答案

您将 name 声明为 char 但随后您尝试将其打印为字符:

printf("added vertex named: %s", newHead->name);

%s 更改为 %c :

printf("added vertex named: %c", newHead->name);

或将您的姓名更改为 char *

关于c - 读取结构中包含的 char 会导致访问冲突异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40807988/

相关文章:

c++ - 通过指针比较聚合类型的成员值

c - 获取位域结构成员的大小

c - pcap 数据链路 LINUX_SLL

c - 了解 C 中的 unsigned char 左旋转

c - 为什么 struct hostent 中的 h_addr_list 是 char ** 而不是 struct in_addr **?

Java:如何遍历类型链接列表的数组并将它们附加到数组

c - 从文件系统中随机选择一个文件

c - 正确使用结构和指针

go - Golang 中的未定义错误

java - 为什么我不能只执行 node = node.next 来迭代链表?