从另一个.c文件中使用函数的函数里面呢? [英] Use a function inside a function from another .c file?
问题描述
我想数组的大小从另一个功能改变。在code编译,但程序崩溃......我坚持,很坚持。这个新的,我的头在旋转上下左,右aaaaah ........
array.c
结构数组{
为int *的数据;
INT大小;
};结构数组* array_create()
{
结构数组*数组=(结构数组*)malloc的(的sizeof(结构数组));
基于阵列>数据=(INT *)malloc的(的sizeof(int)的* 10000);
基于阵列>大小= 10000;
返回数组;
}无效array_resize(结构数组*数组,INT大小)
{
如果(大小>基于阵列>大小){
免费(数组);
基于阵列>数据=(INT *)malloc的(的sizeof(int)的大小*);
} 基于阵列>大小=;
}INT ARRAY_SIZE(结构数组*数组)
{
返回阵列 - >大小;
}
array.h
typedef结构数组*数组;ARRAY array_create();
无效array_resize(结构数组*数组,INT大小);
edit.c
无效编辑()
{
array_resize(阵列,100); //我可以运行code,但程序崩溃
}
的main.c
array数组;
阵= array_create();
编辑(); //程序崩溃
这
无效array_resize(结构数组*数组,INT大小)
{
如果(大小>基于阵列>大小){
免费(数组);
基于阵列>数据=(INT *)malloc的(的sizeof(int)的大小*);
} 基于阵列>大小=;
}
应免费(阵列 - >数据)
不是免费(阵列)
。或者更好的的realloc
返回数组方式>数据
另外,除非你正在寻找的麻烦,声明你的功能,在你的 .H
文件,你在你的 .C $ c执行$ C>文件,例如:
结构数组;
结构体数组* array_create();
和包括 array.h
从 array.c
。
I am trying to change the size of the array from another function. The code compiles but the program crashes... I am stuck, very stuck. New to this, my head is spinning up down left right aaaaah........
array.c
struct array {
int* data;
int size;
};
struct array* array_create()
{
struct array* array = (struct array*) malloc(sizeof(struct array));
array->data = (int*) malloc(sizeof(int) * 10000);
array->size = 10000;
return array;
}
void array_resize(struct array* array, int size)
{
if (size > array->size) {
free(array);
array->data = (int*) malloc(sizeof(int) * size);
}
array->size = size;
}
int array_size(struct array* array)
{
return array->size;
}
array.h
typedef struct array* ARRAY;
ARRAY array_create();
void array_resize(struct array* array, int size);
edit.c
void edit()
{
array_resize(array, 100); // I can run the code but program crashes
}
main.c
ARRAY array;
array = array_create();
edit(); // Program crashes
This:
void array_resize(struct array* array, int size)
{
if (size > array->size) {
free(array);
array->data = (int*) malloc(sizeof(int) * size);
}
array->size = size;
}
Should be free(array->data)
not free(array)
. Or better realloc
array->data
.
Also, unless you are looking for trouble, declare your functions in your .h
files as you do in your .c
files, i.e.:
struct array;
struct array *array_create();
and include array.h
from array.c
.
这篇关于从另一个.c文件中使用函数的函数里面呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!