replax replax - 11 days ago 8
C Question

Reading of a char contained in a struct results in access violation exception

i am trying to implement a linked-list in C with the aim to do a BFS on it.
The input for the list should look like this:

a-bc
b-a
c-a


which represents a list looking like this:

a
/ \
b c


now, my problem is that I cannot read the variable
name
defined in my
Vertex
struct. My program segfaults with Access Reading Violation. While
printf("%s", s)
takes a
char *
, casting the
name
to a
char*
doesn't help. The error takes place before the char is even accessed?

#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;
}


How can I access the value of newHead->name or adjList[i]->name for that matter? The interesting thing is, if I try to access adjList[i]->distance the correct integer is returned...

Answer

You declared name as a char but then you try to print it as a character :

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

Change the %s to %c :

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

or change your name to a char *.