在C中释放2d数组 [英] Freeing a 2d array in C

查看:77
本文介绍了在C中释放2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在研究C编程安静几个月,但每次我遇到一个问题堆栈。如果我们想要释放2d数组会发生什么。我知道我应该使用for循环释放每一行和每列但我不知道我是否正确。



所以这是我的榜样。



我有一个数组,声明用 int



I'm studing C programming for quiet few months now but every time I get stack in one problem. What happens if we want to free a 2d array. I know that I should use a for loop to free each row and column but I don't know if I do it right.

So this is my example.

I have an array wich is declared with int

    int c = 1000;
int array[c][2];





和这里的免费功能:



and here's the free function:

for (int i = 0; i < c; i++) 
	free(array[i]);
	free(array);





当我尝试用gcc编译它我得到以下错误:





When I try to compile it with gcc I get the following errors:

引用:

C: \ Users\George\Desktop> gcc -std = c99 per2.c -o per2.exe

per2.c:在函数'main'中:

per2 .c:86:2:警告:隐式声明函数'free'[-Wimplicit-functi

on-declaration]

free(array [i]);

^

per2.c:86:2:警告:内置函数的不兼容隐式声明'fr

ee'[默认启用] ]

per2.c:87:2:警告:内置函数的不兼容隐式声明'fr

ee'[默认启用]

免费(数组);

^

C:\Users\George\Desktop>gcc -std=c99 per2.c -o per2.exe
per2.c: In function 'main':
per2.c:86:2: warning: implicit declaration of function 'free' [-Wimplicit-functi
on-declaration]
free(array[i]);
^
per2.c:86:2: warning: incompatible implicit declaration of built-in function 'fr
ee' [enabled by default]
per2.c:87:2: warning: incompatible implicit declaration of built-in function 'fr
ee' [enabled by default]
free(array);
^





有什么问题,什么是免费赠送2c的标准公式数组(静态和动态)



Is there any problem and what is the standart formula to free a 2c array (static and dynamic)

推荐答案

arra y在堆栈上声明为静态,因此您不需要(或实际上不能)释放它。



如果你使用 malloc 你需要免费 calloc



祝你好运!
The array is declared static on the stack and you therefor don't need to (or actually can't) free it.

You need to free if you used malloc or calloc.

Good luck!


这篇关于在C中释放2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆