《C Primer Plus》第6版 编程练习 第十二章 第八题

版权声明:此文为博主原创文章,转载请注明出处 https://blog.csdn.net/Alex_mercer_boy/article/details/81865937

目录:

简介:

题目:

 分析:

源代码:

运行测试:


简介:

《C Primer Plus》第6版 编程练习 第十二章 第八题  

如果可以的话,麻烦各位大佬使用 PC 端查看,拜托了,美感真的很重要!!!

编译环境:VS2017 Community

运行平台:Win 10 ×64

题目:

   下面是程序的一部分:             //书上是真的没有注释
    //pe12-8.c
    #include <stdio.h>
    int * make_array(int elem, int val);
    void show_array(const int ar [], int n);
    int main(void)
    {
        int * pa;
        int size;
        int value;

扫描二维码关注公众号,回复: 2900926 查看本文章

        printf("Enter the number of elements: ");
        while (scanf_s("%d", &size) == 1 && size > 0)
        {
            printf("Enter the initialization value: ");
            scanf_s("%d", &value);
            pa = make_array(size, value);
            if (pa)
            {
                show_array(pa, size);
                free(pa)
            }
            printf("Enter the number of elements (1 to quit): ");
        }
        printf("Done.\n");
        return 0;
    }

提供 make_array() 和 show_array() 函数的定义,完成该程序。make_array() 函数接受两个

参数,第一个参数是 int 类型数组的元素个数,第 2 个参数是要赋给每个元素的值。该函数调用

malloc() 创建一个大小合适的数组,将其每个元素设置为指定的值,并返回一个指向该数组的指

针。show_array() 函数显示数组的内容,一行显示 8 个数

 分析:

既然 main() 函数已经给了我们,那我们就只需要扩展就行了。

这道题目重点要求掌握的应该是  动态内存分配 以及 释放动态内存

动态内存分配需要一个指针,以及 molloc() 函数

还需要解决 未分配到内存 ——退出程序

至于赋值什么的,就不必多说了

源代码:

make_array() 函数:-

int * make_array(int elem, int val)
{
	int * ret_val;
	int count;

	//动态内存分配
	ret_val = (int *)malloc(elem * sizeof(int));
	if (ret_val == NULL)					//未分配到内存
	{
		printf("Memory allocation failed. Goodbye!");
		exit(EXIT_FAILURE);
	}
	for (count = 0; count < elem; count++)		
	{
		ret_val[count] = val;				//为每个元素赋值
	}
	return ret_val;
}

show_array() 函数:

void show_array(const int ar[], int n)
{
	int count;

	for (count = 0; count < n; count++)
	{
		if (count % 8 == 0)	    //每 8 个数字换行一次
		{
			putchar('\n');
		}
		printf("%d ", ar[count]);
	}
	putchar('\n');			    //结尾换行
	return;
}

运行测试:

OK,一切搞定!

Alex Mercer(boy) 鸣谢!

猜你喜欢

转载自blog.csdn.net/Alex_mercer_boy/article/details/81865937