我有兩個額外的字符被添加到我的字符串的開頭,我似乎無法找出原因。這些字符甚至不出現在代碼中。我在這裏不知所措。這是我的代碼:額外的字符添加到字符串的開頭?
#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;
}
出於某種原因,該代碼會產生這樣的:
Enter characters: gggg
Input: PEgggg
當它應該是產生這樣的:
Enter characters: gggg
Input: gggg
'input'指向什麼? – immibis
注意:由於'chars'是一個全局變量,'return chars;'沒有意義。 –
@barakmanos最好刪除全局變量,並將它放在本地的'vector'上。 –