игра брюс 2048
Главная / Программирование / Программирование на языке C в Microsoft Visual Studio 2010 / Тест 9

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

Упражнение 1:
Номер 1
Что такое динамическая память?

Ответ:

 (1) оперативная память компьютера, предоставляемая программе до начала ее выполнения 

 (2) оперативная память компьютера, предоставляемая программе во время ее выполнения 

 (3) вся доступная оперативная память, которая может быть выделена программе 


Номер 2
Какое утверждение является верным для динамически распределяемой памяти?

Ответ:

 (1) память выделяется один раз до начала работы программы 

 (2) выделенная область памяти не может быть освобождена до завершения работы программы 

 (3) память предоставляется программе при ее работе 


Номер 3
Какие утверждения являются верными для статически распределяемой памяти?

Ответ:

 (1) память выделяется один раз до начала работы программы 

 (2) выделенная область памяти не может быть освобождена до завершения работы программы 

 (3) память предоставляется программе при ее работе 


Упражнение 2:
Номер 1
Какие утверждения являются верными?

Ответ:

 (1) размер динамически распределяемой области памяти заранее известен 

 (2) динамически распределяемая область памяти не используется программой 

 (3) размер динамически распределяемой области памяти ограничен 


Номер 2
Какие утверждения являются неверными?

Ответ:

 (1) размер динамически распределяемой области памяти заранее известен 

 (2) динамически распределяемая область памяти не используется программой 

 (3) размер динамически распределяемой области памяти неограничен 


Номер 3
Какие утверждения о размере динамически распределяемой области памяти являются верными?

Ответ:

 (1) размер памяти заранее известен 

 (2) размер памяти ограничен 

 (3) размер памяти достаточно большой 


Упражнение 3:
Номер 1
В каком случае память выделяется динамически?
		
	int arr1[10] = {1,2,3,4,5};				(1)
	int *arr2 = (int *)calloc(10, sizeof(int));		(2)
	int *arr3 = (int *)malloc(10*sizeof(int));		(3)
		
		

Ответ:

 (1) в случае (1) 

 (2) в случае (2) 

 (3) в случае (3) 


Номер 2
В каком случае память выделяется динамически?
		
	int arr1[10] = {1,2,3,4,5};				(1)
	int *arr2 = (int *)calloc(10, sizeof(int));		(2)
	int *arr3 = (int *)malloc(10*sizeof(int));		(3)
	int arr4[][3] = {{1,2,3}, {4,5,6}};			(4)
		
		

Ответ:

 (1) в случае (1) 

 (2) в случае (2) 

 (3) в случае (3) 

 (4) в случае (4) 


Номер 3
В каком случае память выделяется статически?
		
	int arr1[10] = {1,2,3,4,5};				(1)
	int *arr2 = (int *)calloc(10, sizeof(int));		(2)
	int *arr3 = (int *)malloc(10*sizeof(int));		(3)
	int arr4[][3] = {{1,2,3}, {4,5,6}};			(4)
		
		

Ответ:

 (1) в случае (1) 

 (2) в случае (2) 

 (3) в случае (3) 

 (4) в случае (4) 


Упражнение 4:
Номер 1
В каком случае будет выделен наибольшой размер памяти?

Ответ:

 (1) int *arr = (int *)malloc(10*sizeof(int)); 

 (2) double *arr = (double *)calloc(6, sizeof(double)); 

 (3) char arr[] = "Lection 10"; 


Номер 2
В каком случае будет выделен наименьший размер памяти?

Ответ:

 (1) int *arr = (int *)malloc(10*sizeof(int)); 

 (2) double *arr = (double *)calloc(6, sizeof(double)); 

 (3) int arr[12] = {1,2,3,4,5}; 


Номер 3
Какой объем памяти будет выделен для хранения массива int arr[12] = {1,2,3,4,5};?

Ответ:

 (1) 5 байт 

 (2) 20 байт 

 (3) 40 байт 

 (4) 48 байт 


Упражнение 5:
Номер 1
Задан фрагмент кода:
		
	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()?	
		

Ответ:

 (1) для увеличения размерности выделяемой памяти 

 (2) для уменьшения размерности выделяемой памяти 

 (3) для реализации дальнейшего добавления символа '!' к строке, заданной пользователем 


Номер 2
При каких значениях размерности 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; 
}
		
		

Ответ:

 (1) n = 4, *ptr = "test" 

 (2) n = 5, *ptr = "test" 

 (3) n = 40, *ptr = "test" 


Номер 3
Необходимо написать программу заполнения одномерного символьного массива заданным числом (вводимым с клавиатуры) символов с добавлением символа восклицательного знака "!" в конце массива символов. При выполнении какой программы не возникнет ошибки в случае, если пользователь задаст размерность n символьного массива равной 4 и строку "test"?

Ответ:

 (1) 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; }  

 (2) 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; }  

 (3) 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; }  


Упражнение 6:
Номер 1
В каком случае при возникновении ошибки при выделении памяти эта ошибка будет корректно обработана?

Ответ:

 (1) ptr = (int *)malloc(size1*sizeof(int)); if (!ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (2) ptr = (int *)malloc(size1*sizeof(int)); if (ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (3) str[i] = (char *) calloc((N+1), sizeof(char)); if (str[i] == NULL) { printf("ERROR. Out of memmory. Press any key: "); _getch(); exit(1); }  


Номер 2
В каком случае при возникновении ошибки при выделении памяти эта ошибка не будет корректно обработана?

Ответ:

 (1) ptr = (int *)malloc(size1*sizeof(int)); if (!ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (2) ptr = (int *)malloc(size1*sizeof(int)); if (ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (3) str[i] = (char *) calloc((N+1), sizeof(char)); if (str[i] == NULL) { printf("ERROR. Out of memmory. Press any key: "); _getch(); exit(1); }  

 (4) ptr = (int *)malloc(30*sizeof(int));  


Номер 3
В каком случае при возникновении ошибки при выделении памяти эта ошибка будет корректно обработана?

Ответ:

 (1) ptr = (int *)malloc(30*sizeof(int));  

 (2) ptr = (int *)malloc(size1*sizeof(int)); if (ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (3) ptr = (int *)malloc(size1*sizeof(int)); if (!ptr) { printf("\nERROR! Out of memory in malloc() function. Press any key: "); _getch(); exit(1); };  

 (4) str[i] = (char *) calloc((N+1), sizeof(char)); if (str[i] == NULL) { printf("ERROR. Out of memmory. Press any key: "); _getch(); exit(1); }  


Упражнение 7:
Номер 1
В каком случае в процессе выполнения программы выполняется перераспределение выделенной памяти с целью ее уменьшения?

Ответ:

 (1) #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> int main(void) { int n, m; char *ptr; printf("\n Enter a dimention of character array: "); scanf_s("%d", &n); _flushall(); ptr = (char *)malloc((n+1)*sizeof(char)); if (!ptr) { printf("\n\t 1st Error! "); printf("\n\n Press any key: "); _getch(); return -1; } printf(" Enter a character array of no more than %d characters: ", n); gets_s(ptr, n+1); m = strlen(ptr); printf("\n Start line:\n"); printf(" %s\n", ptr); ptr = (char *)realloc(ptr, (m+2)*sizeof(char)); if (!ptr) { printf("\n\t 2nd Error! "); printf("\n\n Press any key: "); _getch(); return -1; } strcat_s(ptr, m+2, "!"); printf("\n Start line and character \"%c\":\n", '!'); printf(" %s\n", ptr); free (ptr); printf("\n\n Press any key: "); _getch(); return 0; }  

 (2) #include <stdio.h> #include <stdlib.h> #define N 10 int main(void) { int i, n = 0; int arr1[N] = {1,2,3,4,5}, *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; i++) { arr[i] = i+1; n++; 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; }  

 (3) #include <stdio.h> #include <stdlib.h> #define N 10 int main(void) { int i, n = 0; int arr1[N] = {1,2,3,4,5}, *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<5; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; free(arr); return 0; }  


Номер 2
В каком случае в процессе выполнения программы выполняется перераспределение выделенной памяти с целью ее увеличения?

Ответ:

 (1) #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> int main(void) { int n, m; char *ptr; printf("\n Enter a dimention of character array: "); scanf_s("%d", &n); _flushall(); ptr = (char *)malloc((n+1)*sizeof(char)); if (!ptr) { printf("\n\t 1st Error! "); printf("\n\n Press any key: "); _getch(); return -1; } printf(" Enter a character array of no more than %d characters: ", n); gets_s(ptr, n+1); m = strlen(ptr); printf("\n Start line:\n"); printf(" %s\n", ptr); ptr = (char *)realloc(ptr, (m+2)*sizeof(char)); if (!ptr) { printf("\n\t 2nd Error! "); printf("\n\n Press any key: "); _getch(); return -1; } strcat_s(ptr, m+2, "!"); printf("\n Start line and character \"%c\":\n", '!'); printf(" %s\n", ptr); free (ptr); printf("\n\n Press any key: "); _getch(); return 0; }  

 (2) #include <stdio.h> #include <stdlib.h> #define N 10 int main(void) { int i, n = 0; int arr1[N] = {1,2,3,4,5}, *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; i++) { arr[i] = i+1; n++; 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; }  

 (3) #include <stdio.h> #include <stdlib.h> #define N 10 int main(void) { int i, n = 0; int arr1[N] = {1,2,3,4,5}, *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<5; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; free(arr); return 0; }  


Номер 3
В процессе выполнения приведенной программы возникает ошибка:
		
#include <stdio.h>
#include <stdlib.h>
#define N 10

int 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;
}
	
Каким образом можно изменить программу для ее корреткной работы?	
		

Ответ:

 (1) выделить больший размер памяти в функции calloc() 

 (2) добавить операцию перераспределения памяти 

 (3) изменить процедуру заполнения массива, изменив условие выхода из цикла на i<N 


Упражнение 8:
Номер 1
После выполнения какой программы будет выполняться условие size2 < size3?

Ответ:

 (1) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; printf("arr[%d] = %d\n", i, arr[i]); } size2 = N*sizeof(int); for (i=0; i<N/2; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; size3 = N*sizeof(int); free(arr); return 0; }  

 (2) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; printf("arr[%d] = %d\n", i, arr[i]); } size2 = N*sizeof(int); for (i=0; i<N/2; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; size3 = n*sizeof(int); free(arr); return 0; }  

 (3) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; }  


Номер 2
После выполнения какой программы будет выполняться условие size2 > size3?

Ответ:

 (1) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; printf("arr[%d] = %d\n", i, arr[i]); } size2 = N*sizeof(int); for (i=0; i<N/2; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; size3 = N*sizeof(int); free(arr); return 0; }  

 (2) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; printf("arr[%d] = %d\n", i, arr[i]); } size2 = N*sizeof(int); for (i=0; i<N/2; i++) { arr[i] = i+1; n++; } arr = (int *)realloc(arr, n*sizeof(int)); if (!arr) { printf("\nERROR! Out of memory in realloc() function. Press any key: "); _getch(); exit(1); }; size3 = n*sizeof(int); free(arr); return 0; }  

 (3) #include <stdio.h> #include <stdlib.h> #define N 10 int 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; }  


Номер 3
Какое утверждение будет верным после выполнения приведенной программы?
		
#include <stdio.h>
#include <stdlib.h>
#define N 10

int 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;
}
			
		

Ответ:

 (1) size1 > size2 

 (2) size2 < size3 

 (3) size1 = size 3 


Упражнение 9:
Номер 1
В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		
#include <stdio.h>
#include <stdlib.h>
#define N 10

int 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;
}
	
Определите, есть ли в этой программе ошибки?	
		

Ответ:

 (1) в программе нет ошибок 

 (2) используется неинициализированный указатель 

 (3) выполняется неверное перераспределение памяти 

 (4) выполняется неверное освобождение памяти 


Номер 2
В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		
#include <stdio.h>
#include <stdlib.h>
#define N 10

int 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;
}
	
Какие изменения нужно внести в программу для ее корректной работы?	
		

Ответ:

 (1) для корректной работы программы не требуются изменения 

 (2) изменить размер в функции выделения памяти 

 (3) изменить синтаксис функции освобождения памяти 

 (4) инициализировать указатель arr 


Номер 3
В приведенной программе выполняется перераспределение памяти для увеличения размерности массива:
		
#include <stdio.h>
#include <stdlib.h>
#define N 10

int 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;
}
	
Какие изменения необходимо внести в программу для ее корректной работы?	
		

Ответ:

 (1) для корректной работы программы не требуются изменения 

 (2) для выделения памяти для хранения массива всегда должна использоваться функция calloc(N, sizeof(int)) 

 (3) добавление новых элементов в массив должно выполняться до перераспределения памяти 


Упражнение 10:
Номер 1
Задан указатель double **m на массив указателей:
		
	int i;
	double **m;
	m = (double **)calloc(10,sizeof(double *));

	for (i=0; i<10; i++)
		m[i] = (double *)calloc(5,sizeof(double));
	
Как в данном случае освободить выделенную память?		
		

Ответ:

 (1) for (i=0; i<10; i++) free(m[i]);  

 (2) free(m);  

 (3) for (i=0; i<10; i++) free(m[i]); free(m);  


Номер 2
Задан указатель int **m на массив указателей:
		
	int i;
	int **m;
	m = (int **)calloc(5,sizeof(int *));

	for (i=0; i<5; i++)
		m[i] = (int *)calloc(3,sizeof(int));
	
Как в данном случае освободить выделенную память?		
		

Ответ:

 (1) for (i=0; i<10; i++) free(m[i]);  

 (2) free(m);  

 (3) for (i=0; i<5; i++) free(m[i]); free(m);  

 (4) for (i=0; i<3; i++) free(m[i]); free(m);  

 (5) for (i=0; i<15; i++) free(m[i]); free(m);  


Номер 3
При какой инициализации указателя int **m на массив указателей необходимо выполнить освобождение памяти приведенным способом?
		
	for (i=0; i<5; i++) free(m[i]);
	free(m);
			
		

Ответ:

 (1) int i; int **m; m = (int **)calloc(3,sizeof(int *)); for (i=0; i<3; i++) m[i] = (int *)calloc(5,sizeof(int));  

 (2) int i; int **m; m = (int **)calloc(5,sizeof(int *)); for (i=0; i<5; i++) m[i] = (int *)calloc(3,sizeof(int));  

 (3) int i; int **m; m = (int **)calloc(10,sizeof(int *)); for (i=0; i<10; i++) m[i] = (int *)calloc(5,sizeof(int));  


Упражнение 11:
Номер 1
В каком случае будет выделена память под двухмерный массив размером 4х10?

Ответ:

 (1) int *arr = (int *)malloc((4*10)*sizeof(int));  

 (2) int i; int **m; m = (int **)calloc(10,sizeof(int *)); for (i=0; i<10; i++) m[i] = (int *)calloc(4,sizeof(int));  

 (3) int (*p)[10]; p = malloc(40*sizeof(int));  


Номер 2
В каком случае будет выделена память под двухмерный массив размером 10х4?

Ответ:

 (1) int *arr = (int *)malloc((4*10)*sizeof(int));  

 (2) int i; int **m; m = (int **)calloc(10,sizeof(int *)); for (i=0; i<10; i++) m[i] = (int *)calloc(4,sizeof(int));  

 (3) int (*p)[10]; p = malloc(40*sizeof(int));  


Номер 3
Под какой массив выделяется память в приведенном фрагменте кода?
		
	int (*p)[10]; 
	p = malloc(40*sizeof(int));
		
		
		

Ответ:

 (1) под одномерный массив размерностью 10 

 (2) под одномерный массив размерностью 40 

 (3) под двухмерный массив размерностью 4х10 

 (4) под двухмерный массив размерностью 10х4 


Упражнение 12:
Номер 1
Каким может быть время жизни динамических переменных?

Ответ:

 (1) от точки создания до конца программы 

 (2) от точки создания до явного освобождения памяти 

 (3) от точки создания до конца работы операционной системы 


Номер 2
Какие утверждения являются верными?

Ответ:

 (1) динамические переменные существуют от точки создания до явного освобождения памяти 

 (2) динамические переменные существуют от точки создания до конца работы операционной системы 

 (3) динамические переменные существуют от точки создания до конца программы 


Номер 3
Какое утверждение является неверным?

Ответ:

 (1) динамические переменные существуют от точки создания до явного освобождения памяти 

 (2) динамические переменные существуют от точки создания до конца работы операционной системы 

 (3) динамические переменные существуют от точки создания до конца программы 




Главная / Программирование / Программирование на языке C в Microsoft Visual Studio 2010 / Тест 9