Необходимо написать программу заполнения одномерного символьного массива заданным числом (вводимым с клавиатуры) символов с добавлением символа восклицательного знака "!" в конце массива символов. При выполнении какой программы не возникнет ошибки в случае, если пользователь задаст размерность n символьного массива равной 4 и строку "test"?
(Отметьте один правильный вариант ответа.)
Варианты ответа
int main(void) { int n, m; char *ptr; printf("\nEnter a dimention of character array: "); scanf_s("%d", &n); _flushall(); ptr = (char *)malloc((n+1)*sizeof(char)); if (!ptr) { printf("\nERROR! Out of memmory (error in malloc() function). Press any key..."); _getch(); exit(1); } printf("Enter a character array (not more than %d characters): ", n); gets_s(ptr, n+1); m = strlen(ptr); printf("\nStart line: %s", ptr); strcat_s(ptr, m+2, "!"); printf("\nStart line and character \"%c\": %s", '!', ptr); free (ptr); printf("\n\nPress any key: "); _getch(); return 0; }
int main(void) { int n, m; char *ptr; printf("\nEnter a dimention of character array: "); scanf_s("%d", &n); _flushall(); ptr = (char *)malloc((n+1)*sizeof(char)); if (!ptr) { printf("\nERROR! Out of memmory (error in malloc() function). Press any key..."); _getch(); exit(1); } printf("Enter a character array (not more than %d characters): ", n); gets_s(ptr, n+1); m = strlen(ptr); printf("\nStart line: %s", ptr); ptr = (char *)realloc(ptr, (m+2)*sizeof(char)); if (!ptr) { printf("\nERROR! Out of memmory (error in realloc() function). Press any key..."); _getch(); exit(1); } strcat_s(ptr, m+2, "!"); printf("\nStart line and character \"%c\": %s", '!', ptr); free (ptr); printf("\n\nPress any key: "); _getch(); return 0; } (Верный ответ)
int main(void) { int n, m; char *ptr; printf("\nEnter a dimention of character array: "); scanf_s("%d", &n); _flushall(); ptr = (char *)malloc(n*sizeof(char)); if (!ptr) { printf("\nERROR! Out of memmory (error in malloc() function). Press any key..."); _getch(); exit(1); } printf("Enter a character array (not more than %d characters): ", n); gets_s(ptr, n+1); m = strlen(ptr); printf("\nStart line: %s", ptr); strcat_s(ptr, m+2, "!"); printf("\nStart line and character \"%c\": %s", '!', ptr); free (ptr); printf("\n\nPress any key: "); _getch(); return 0; }