7-55 实验10_7_动态分配内存_2 (100 分)

已知正整数n、m,你要利用malloc函数动态开辟一个n行、m列的整型二维数组,然后读取nm个整数存入该数组中。再将这nm个整数全部改为其相反数的10倍,然后将其输出。最后你要利用free函数将该动态数组所占用的空间释放。

提示:malloc与free的使用,以下代码即建立了一个n行m列的整型二维动态数组,并释放:

干货,下次要申请二维动态数组就知道则么弄了

int **a,n ,m;
scanf(“%d%d”,&n,&m);
a=(int **)malloc(sizeof(int *)*n);//建立长度为n的动态指针数组
for(i=0;i<n;i++)
a[i]=(int *)malloc(sizeof(int)*m);//建立长度为m的一维整型数组
for(i=0;i<n;i++)
free(a[i]);
free(a);//释放动态内存。

输入格式:

输入为两行,第一行为两个用空格分隔的正整数n,m,第二行为n*m个用空格分隔整数。测试用例保证所有整数可以用int存储,且为这n*m个整数申请内存不会超出内存限制。

输出格式:

输出按矩阵格式输出,具体见样例。

输入样例:

3 4
1 2 3 4 5 6 7 8 9 10 11 12

输出样例:

-10 -20 -30 -40
-50 -60 -70 -80
-90 -100 -110 -120

代码如下:

#include<stdio.h>
#include<stdlib.h>
//要引用头文件
int main()
{
	//动态开辟二维数组
	int** a, m, n,i,j;
	scanf("%d %d", &n, &m);
	//申请动态数组
	a = (int**)malloc(sizeof(int*) * n);
	for (i = 0; i < n; i++)
		a[i] = (int*)malloc(sizeof(int) * m);
	//输入数组
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", &a[i][j]);
	//对数组的操作
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			a[i][j] *= (-10);
	//输出数组
	for (i = 0; i < n; i++)
	{
		printf("%d",a[i][0]);
		for (j = 1; j < m; j++)
			printf(" %d", a[i][j]);
		printf("\n");
	}
	//释放内存
	for (i = 0; i < n; i++)
		free(a[i]);
	free(a);
	return 0;
}

这里看看malloc函数

Allocate memory block

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

 看有道(ohhh)

分配内存块分配一个大小为字节的内存块,返回一个指向块开头的指针。新分配的内存块的内容没有初始化,保留不确定的值。如果size为0,则返回值取决于特定的库实现(它可能是一个空指针,也可能不是),但返回的指针不应被解引用。


/* malloc example: random string generator*/
#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main ()
{
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);

  return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值