0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Richie please don't post "thank you" in the comments, the comment section is not for that. If you think that the answer is good, upvote and if you think it's the one that solves your problem, then accept it. That's the proper way of "thanking" in Stack Overflow.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.