Mam dwa dodatkowe znaki dodawane do początku mojego napisu i nie mogę wydawać się dowiedzieć dlaczego. Postacie nie pojawiają się nawet w kodzie. Brak mi tutaj. To jest mój kod:Dodatkowe znaki dodane do początku ciągu?
#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;
}
Z jakiegoś powodu, kod produkuje to:
Enter characters: gggg
Input: PEgggg
Kiedy należy produkujących to:
Enter characters: gggg
Input: gggg
Na co wskazuje 'input'? – immibis
Nota boczna: ponieważ 'chars' jest zmienną globalną, nie ma sensu w' zwracających znakach; '. –
@barakmanos byłoby lepiej usunąć zmienną globalną i mieć ją lokalną do 'wektora' –