strcat treats its argument as a pointer to a null-terminated string. Throwing away a char in char * just dangerous, and I canβt imagine why it would never be useful (not implying that you are stupid for trying it), everyone makes stupid mistakes when they learn. here.)
The reason is that it will interpret a single char byte, plus the extra sizeof(char*) - sizeof(char) (usually 3) bytes surrounding this char , as a pointer that will point to ... anywhere. You have no way of knowing where it points, since 3 of these bytes are out of your control and therefore do not know if it points to reliable data.
You can use this as a second approach:
strcat(inp, &c);
This time you will be better, since &c is an expression of type char * , and no deviations are required. But then again, strcat assumes that the argument is a null-terminated string, and since you cannot guarantee a null byte after your char data, this will not happen.
The best way:
size_t len = strlen(inp); // this may already be calculated somewhere else ... inp[len++] = c; // add c as the last character, and adjust our len inp[len] = '\0'; // add a new nul terminator to our string
UPDATE:
Actually, I lied. The best way is to use the standard fgets library function, which seems to do more or less what you are trying to do. Honestly, I forgot about it, but if this is homework, your professor may not want you to use fgets so you can learn to do it manually. However, if this is not homework, fgets does exactly what you are looking for. (Actually, the third approach is well suited for overriding the functionality of fgets or fgets .)
I would also add some other comments to your input function:
char* inp = ""; will point to read-only data. A flaw in the C standard (for backward compatibility) allows you to assign string literals to char* types instead of const char * types, since it (IMHO) should be.
There are several ways to approach this, but best of all is dynamic allocation. Use the malloc function to reserve some data, track how much you used in your function, and use the realloc function if you need more space to store it. If you need help with this, I am sure you will come back here (hopefully not soon) with another question. :)getchar() returns int since EOF is defined outside the normal range of a char . To distinguish between any char and EOF , it is best to do c a int . Otherwise, a valid character may signal EOF . Be sure to add c to char if you add it to the string.
source share