0

this question has been asked in different ways, but hasn't been answered I think for the way I wrote my code.

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    string n = get_string();
    int i = 0;
    if (n != NULL)
    {
        printf("%c", toupper(n[i]));
    }
    while (n[i] != '\0')
    {
       while (n[i] != ' ')
        {
            i++;
        }
        i++;
        printf("%c", toupper(n[i])); 
    }
    printf("\n");
}

If I were to plug in "John Smith" into the code, It would return the right result, JS, but be displayed like this "JSSegmentation Fault" which shouldn't be happening. COuld someone possibly take a look and see what I have made a mistake on?

0

Think about what is happening at the end of the string and how it interacts with the nested while loops. Let's say that the name string is Fred. First, the F is printed out. If the program works correctly, nothing else should print and the program should end normally.

However, it gets into the inner while loop and will loop until it finds the ASCII code for a space, or if it doesn't find a space, it becomes an "infinite loop". Since there is no space in Fred\0, it's just going to keep incrementing i until something unpredictable happens. The inner while loop is coded to ONLY look for a space, so it blows right past the end of string marker. The system won't prevent this. Either it will find some random data in the memory space that matches the ASCII code for a space, or it will increment until n[i] is outside of the memory space or i overflows.

This scenario is the same no matter how many first, middle or last names are in the string. It happens this way on the last name in the string every time, unless the very last char is a space.

You need to rethink things a little and recode to deal with this.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .