Это был фрагмент кода, который я написал для своего задания, некоторые странные конструкции кода не контролируются мной.В настоящее время я пишу их на MacOS.
file1
#include <stdio.h>
extern int read_palindrome();
int main()
{
if (read_palindrome()) printf("input is a palindrome");
else printf("input is not a palindrome");
return 0;
}
file2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_palindrome2(char *, int);
// malloc() will be used as usual to set aside an initial memory
// The entire input will be read gradually by characters using getchar()
// In the event we require more memory than what we have previously,
// use realloc() to increase memory size dynamically
int read_palindrome() {
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
int i = 0;
int c = EOF;
if (pStr == NULL) {
return -1;
}
while (( c = getchar() ) != '\n') {
pStr[i] = (char)c;
i++;
if(i == current_size) {
current_size += len_max;
char *tmp = realloc(pStr, current_size);
if (tmp == NULL) {
free(pStr);
return -1;
}
pStr = tmp;
}
}
int retval = check_palindrome2(pStr,i);
free(pStr);
return retval;
}
int check_palindrome2(char *s, int length) {
for (int i = 0; i < length / 2; i++) {
if (s[i] != s[length-i-1])
return 0;
}
return 1;
}
Я думаю, что этот код работает, за исключением пустых файлов, что приведет к моей программепостоянно ожидать ввода и не прекращаться.Тем не менее, я понял, что при использовании Sublime Text создание файла test.in без нажатия «Enter» как-то отображает поведение «без завершения», а ввод чего-либо в vim без нажатия «Enter» для новой строки все еще позволяет кодуРабота.Кто-нибудь знает причину этого явления?