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

int main(void)
{

    printf("type your name: ");
    string name = GetString();
    string initial = NULL;



    for(int i = 0, n=strlen(name);i<n;i++)
    {
        if(i==0)
        initial += name[i];
        if(name[i]==' ')
        initial += name[i+1];
    }
    for(int i = 0,n=strlen(initial);i<n;i++)
    {
        if(initial[i]>='a'&&initial[i]<='z')
        initial[i] = initial[i]-32;
    }
    printf("%s",initial);
}

The code seems to work when I compile it, but if I operate the code and type some letters in, then segmentation fault(core dumped) error comes up. Is there anything wrong with the code? Can somebody pick some faults in the code out, please?

1

You initialize string initial = NULL
But in your 2nd for loop, you set n=strlen(initial)

0

Unlike other newer languages, in C you can't change the length of a string (in fact char*) on runtime and you can't concatenate two strings using the + operator. In fact, you don't have to save the initials to a new variable, you just have to print them, using the printf() function, on one line, one by one, and at the end print a newline. If you want to save them nevertheless your best bet is to declare initial like that:

char initial[strlen(name) + 1];

because in any case and initial letters will never be more than the letters in the name. With some reasoning you can reduce the allocated length farther, but I said earlier you don't have to.

You must log in to answer this question.

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