Reputation: 73
Recently I learned about linked lists and wrote a simple program from a youtube tutorial, which simply adds some racingcars in a linked list with their names and their speed. However everything is working fine just the output from the console seems strange to me.
Console:
Car: 1 Name: mercedes� Speed: 200
Car: 2 Name: redBull Speed: 250
Car: 3 Name: ferrari Speed: 300
Car: 4 Name: mcLaren Speed: 10
Total Cars: 4
As you can see I'm wondering about the strange �
.
Code:
#include "stdio.h"
#include "string.h"
typedef struct S_racingCar
{
char name[8];
int speed;
struct S_racingCar *next;
} racingCar;
void printList(racingCar *start)
{
racingCar *currentCar = start;
int count = 0;
while(currentCar != NULL)
{
count++;
printf("Car: %d Name: %s Speed: %d\n", count, currentCar->name, currentCar->speed);
currentCar = currentCar->next;
}
printf("Total Cars: %d\n", count);
}
int main()
{
racingCar mercedes = { "mercedes", 200, NULL};
racingCar redBull = { "redBull", 250, NULL};
racingCar ferrari = { "ferrari", 300, NULL};
racingCar mcLaren = { "mcLaren", 10, NULL};
mercedes.next = &redBull;
redBull.next = &ferrari;
ferrari.next = &mcLaren;
printList(&mercedes);
return 0;
}
Upvotes: 0
Views: 28
Reputation: 2097
It's because you have name defined as char[8]
, and "mercedes"
has 8 characters, but printf
expects an end of line character at the end, so you need it to be 9 chars to use it like that without a side-effect from printf
.
Upvotes: 0
Reputation: 12669
The length of name
structure member is 8
and "mercedes"
is also of length 8
. There is no space left for null character \0
. Try increasing the size of name
.
In C language, a string is a null-terminated array of characters. The buffer should be long enough to accommodate the terminating null-character \0
.
Upvotes: 1