DEV Community

Shanxx
Shanxx

Posted on

CS50x : Practice Problems (Debug)

Problem link

Given Code

This is a code with bug that you will solve

// Become familiar wih C syntax
// Learn to debug buggy code

#include <cs50.h>

int main(void)
{
    // Ask for your name and where live
    name = get_string("What is your name? ")
    location = get_string("Where do you live? ")

    // Say hello
    print("Hello, %i, from %i!", name, location)
}

Enter fullscreen mode Exit fullscreen mode

Bug 1

You'll see that it will give you this error when running/typing make debug

debug.c:9:5: error: use of undeclared identifier 'name'
    name = get_string("What is your name? ")
    ^
1 error generated.
make: *** [<builtin>: debug] Error 1
Enter fullscreen mode Exit fullscreen mode

to solve this we need to add what type is the name is it string? yes!!
see this
change the code like this

    string name = get_string("What is your name? ");
    string location = get_string("Where do you live? ");
Enter fullscreen mode Exit fullscreen mode

and also always don't forget the semi colon in the last line or else you will get this error

debug.c:9:52: error: expected ';' at end of declaration
    string name = get_string("What is your name? ")
                                                   ^
                                                   ;
1 error generated.
Enter fullscreen mode Exit fullscreen mode

Bug 2

debug.c:13:5: error: implicit declaration of function 'print' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
    print("Hello, %i, from %i!", name, location)
    ^
Enter fullscreen mode Exit fullscreen mode

This codes means there's no print syntax on c language.
To solve this we need to change print to printf
and also don't forget to add #include <stdio.h> in the top above/below the #include <cs50.h> or else the printf will not work

Bug 3

Now for the last bug!!

debug.c:13:35: error: format specifies type 'int' but the argument has type 'string' (aka 'char *') [-Werror,-Wformat]
    printf("Hello, %i, from %i!", name, location)
                   ~~             ^~~~
                   %s
Enter fullscreen mode Exit fullscreen mode

as the error say we cant put i in there because the name is a string not an number we can only add %i if the variable is a number

so to fix this change the 2 %i into %s because they are both strings and also add semi colon in the last part
like this

printf("Hello, %s, from %s!", name, location);

Solution

// Become familiar wih C syntax
// Learn to debug buggy code
#include <stdio.h>
#include <cs50.h>



int main(void)
{
    // Ask for your name and where live
    string name = get_string("What is your name? ");
    string location = get_string("Where do you live? ");

    // Say hello
    printf("Hello, %s, from %s!", name, location);
}


Enter fullscreen mode Exit fullscreen mode

yosh!!!

Top comments (0)