База ответов ИНТУИТ

Программирование на языке C в Microsoft Visual Studio 2010

<<- Назад к вопросам

В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		#include <stdio.h>#include <stdlib.h>#define N 10int main(void){	int i;	int *arr = (int *)malloc(N*sizeof(int));		if (!arr) {		printf("\nERROR! Out of memory in calloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=0; i<N; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);			}	arr = (int *)realloc(arr, (N+2)*sizeof(int));	if (!arr) {		printf("\nERROR! Out of memory in realloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=N; i<N+2; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);	}	free(arr);	return 0;}
Какие изменения необходимо внести в программу для ее корректной работы?

(Отметьте один правильный вариант ответа.)

Варианты ответа
для корректной работы программы не требуются изменения(Верный ответ)
для выделения памяти для хранения массива всегда должна использоваться функция calloc(N, sizeof(int))
добавление новых элементов в массив должно выполняться до перераспределения памяти
Похожие вопросы
В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		#include <stdio.h>#include <stdlib.h>#define N 10int main(void){	int i;	int *arr;	arr = (int *)realloc(arr, (N+2)*sizeof(int));	for (i=0; i<N; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);			}	if (!arr) {		printf("\nERROR! Out of memory in realloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=N; i<N+2; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);	}	free(arr);	return 0;}
Какие изменения нужно внести в программу для ее корректной работы?
В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		#include <stdio.h>#include <stdlib.h>#define N 10int main(void){	int i;	int *arr;	for (i=0; i<N; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);			}	arr = (int *)realloc(arr, (N+2)*sizeof(int));	if (!arr) {		printf("\nERROR! Out of memory in realloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=N; i<N+2; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);	}	free(arr);	return 0;}
Определите, есть ли в этой программе ошибки?
Какое утверждение будет верным после выполнения приведенной программы?
		#include <stdio.h>#include <stdlib.h>#define N 10int main(void){	int size1, size2, size3, i, n = 0;	int arr1[N] = {1,2,3,4,5}, *arr;		size1 = sizeof(arr1);	arr = (int *)calloc(N, sizeof(int));	if (!arr) {		printf("\nERROR! Out of memory in calloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=0; i<N; i++) {		arr[i] = i+1;		n++;		printf("arr[%d] = %d\n", i, arr[i]);			}	size2 = N*sizeof(int);	arr = (int *)realloc(arr, (N+2)*sizeof(int));	if (!arr) {		printf("\nERROR! Out of memory in realloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=N; i<N+2; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);	}	for (i=0, n=0; i<N+2; i++) n++;	size3 = n*sizeof(int);	free(arr);	return 0;}
В процессе выполнения приведенной программы возникает ошибка:
		#include <stdio.h>#include <stdlib.h>#define N 10int main(void){	int i;	int *arr;		arr = (int *)calloc(N, sizeof(int));	if (!arr) {		printf("\nERROR! Out of memory in calloc() function. Press any key: ");		_getch(); 		exit(1); 	};	for (i=0; i<N+2; i++) {		arr[i] = i+1;		printf("arr[%d] = %d\n", i, arr[i]);	}	free(arr);	return 0;}
Каким образом можно изменить программу для ее корреткной работы?
Задан фрагмент кода:
			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);
В запросе размерности массива пользователь задал 80. В запросе ввода строки пользователь ввел строку "Lection 9". Для чего в данном случае будет использована функция realloc()?
При каких значениях размерности n символьного массива и строки, на которую указывает указатель ptr, в результате выполнения приведенной программы возникнет ошибка?
		#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <string.h>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);	strcat_s(ptr, m+2,  "!");	printf("\nStart line and character \"%c\": %s", '!', ptr);		free (ptr);	printf("\n\nPress any key: ");	_getch();	return 0; }
Какие утверждения являются верными для приведенной программы?
void fillOnly(int);void free_n(int);void fill_n(int);int main (void) {	int n = 1; 	int in = 1; 	printf("\n Enter a length of string (naturel number): ");	in = scanf_s("%i", &n);	if (in != 1 || n < 1 || n > 15)     {		printf("\n Error input. Press any key to exit: ");		_getch();		exit(0);	}	puts("\n\tResult:");	fill_n(n);	printf("\n\n Press any key to exit: ");	_getch();	return 0;}void fillOnly(int n) {	if (n == 1)		printf("\t%+3d\n", 1);	else {		fillOnly(n-1);		printf("\t%+3d\n", n);		free_n(n-1);	}}void free_n(int n) {	if (n == 1)		printf("\t%+3d\n", -1);	else {		fillOnly(n-1);		printf("\t%+3d\n", -n);		free_n(n-1);	}}void fill_n(int n) {	if (n == 1)		printf("\t%+3d\n", 1);	else {		if (n == 2)			printf("\t%+3d\n\t%+3d\n", 1, 2);		else {			fillOnly(n-1);			printf("\t%+3d\n", n);			fill_n(n-2);		}	}}
Задана программа, в которой выполняется подключение файла arr.h:
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <locale.h>#ifndef ARR#define ARR#include "arr.txt"#endifint main (void)  {	int i = 0 , j = 0, n;		setlocale (LC_ALL, "rus");	printf("Введите количество человек (от 1 до 3): ");	scanf("%d", &n);    	if (n<1 || n>3) {		printf("Ошибка ввода данных. Нажмите любую клавишу: ");		_getch();		exit(1);	}	#undef ARR	#ifdef ARR		for (i=0; i<n; i++)			printf("%d. %s %s\n", i+1, names[i], surnames[i]);	#endif	return 0;}
Содержание файла arr.h:
char *names[] = {"Иван", "Пётр", "Илья"};char *surnames[] = {"Иванов", "Пётров", "Ильин"};
Определите, будут ли выведены на экран сочетания имён и фамилий из файла arr.h при выполнении приведенной программы? Если не будут, то почему?
Приведенная программа выводит на экран сочетания имён и фамилий, которые хранятся в подключаемом файле arr.txt:
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <locale.h>#ifndef ARR	#define ARR	#include "..\arr.txt"#endifint main (void)  {	int i = 0 , j = 0, n;		setlocale (LC_ALL, "rus");	printf("Введите количество человек (от 1 до 3): ");	scanf("%d", &n);    	if (n<1 || n>3) {		printf("Ошибка ввода данных. Нажмите любую клавишу: ");		_getch();		exit(1);	}	#ifdef ARR		for (i=0; i<n; i++)			printf("%d. %s %s\n", i+1, names[i], surnames[i]);	#endif	return 0;}
Содержание файла arr.txt:
char *names[] = {"Иван", "Пётр", "Илья"};char *surnames[] = {"Иванов", "Пётров", "Ильин"};
Где должен храниться подключаемый файл?
Каким будет результат выполнения приведенной программы?
#include <stdio.h>#include <string.h>#define N 10int main(){			char strLow[N];	int i;	printf("Enter string in low register (%d symbols): \n", N);	scanf("%s", strLow);	for (i=0; i<strlen(strLow); i++)		putchar(strLow[i] - 32);	printf("\n");	return 0;}