I have two extra characters that are added to the beginning of my line, and I cannot understand why. Characters are not even displayed in the code. I'm at a loss here. This is my code:
#include <stdlib.h> #include <stdio.h> #include <string.h> char *chars; char* vector(char input, char *newlist); int main(){ char *input, *out = "Input: "; printf("Enter characters: "); while(1){ char i = getchar(); //get input if(i == '\n'){ break; //detect a return key } else{ input = vector(i, input); //call vector } } char * print = (char *)malloc(1 + strlen(input) + strlen(out)); strcpy(print, out); //concat the strings strcat(print, input); printf("\n%s", print); //print array free(print); free(input); free(chars); return 0; //exit } char* vector(char in, char *newlist){ int length = strlen(newlist); //determine length of newlist(input) chars = (char*)calloc(length+2, sizeof(char)); //allocate more memory strcpy(chars, newlist); //copy the array to chars chars[length] = in; //appened new character chars[length + 1] = '\0'; //append end character return chars; }
For some reason, the code produces this:
Enter characters: gggg Input: PEgggg
When should this be done:
Enter characters: gggg Input: gggg
c
Nickname97
source share