-2

I am working on a initials project where you enter a name and it prints the initials. When I try and combine the strings it returns Segmentation fault instead of the initials.

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

int main(void) {
    printf("Name: ");
    string name = GetString();
    printf("\n");

    int length = strlen(name);
    string initials = "";
    int arraylength = length + 1;
    char string[arraylength];
    string[0] = toupper(name[0]);
    int count = 1;
    for(int l = 1;l<=length;l++) {
        if(name[l] == ' ') {
        l++;
        count++;
        string[l] = toupper(name[l]);
    }
}
count++;
string[count] = '\0';
for(int c = 0;c<=count;c++) {
    strcat(initials, &string[c]);
}
printf("%s\n", initials);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Marcus Mardis
  • 83
  • 1
  • 1
  • 8
  • 3
    Q: what exactly is this "string" in your program? Can you copy/psate the definition for `string`, and the prototype for`GetString()` into your post? And you can't use `strcat()` with a "char" variable. – paulsm4 Jan 24 '16 at 23:25
  • 2
    @paulsm4 Search for the *cs50.h* I couldn't believe it when I saw it yesterday. – Iharob Al Asimi Jan 24 '16 at 23:29

1 Answers1

3

That's why a string type would cause confusion, you make a pointer to a single char. And you then pass it to strcat() that's simply wrong.

A string, as expected by strlen() or strcat() or all str* functions, is not simple a char pointer which is what the type string in your code is.

In a is actually a sequence of bytes with the last byte being '\0', and it's not optional. You create a pointer to a single char and that is not the same as a string that I just described.

Any of the str* functions will try to find the '\0' but since you passed the address of a stack variable which is not an array, the behavior is undefined when any of these functions try to increment and dereference the passed pointer.

When you do understand how strings work in you would see that using strcat() for the concatenation of many chunks of a large string together is not very efficient, you would also know that you just need to append a single char and that you can by simply using index notation, like

char string[8];

string[0] = 'E';
string[1] = 'x';
string[2] = 'a';
string[3] = 'm';
string[4] = 'p';
string[5] = 'l';
string[6] = 'e';
string[7] = '\0'; // The very necessary terminator
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97