【发布时间】:2021-04-16 03:38:36
【问题描述】:
我在大学时被要求用 C 语言构建一个函数,该函数从文件中读取多个值,然后使用指针(它必须使用指针)将内存动态分配给通过引用传递的数组,然后我们需要显示使用另一个函数读取的值。
我尝试了两种我在这里展示的方法:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
///Read an 1d array from the file stuff.txt inside of a function
/// and dinamically allocate memory
/// after that display on the screen the values readed from file
void getDataFirstFunction(int **a, int *n)
{
FILE *f;
f = fopen("stuff.txt" ,"r");
if(!f)
{
printf("ERROR WHILE OPENING THE FILE!!");
exit(0);
} else
{
int d;
fscanf(f,"%d",&(*n));
///we dinamically alocate memory
a = calloc((*n),sizeof(int));
int i=0;
while(!feof(f))
{
fscanf(f,"%d",&a[i++]);
}
}
///if I try to display the values here it works
///but when I try to read display them in the display
///function it is not going to work anymore
fclose(f);
}
int * getData(int **a,int *n)
{
FILE *f;
f = fopen("stuff.txt" ,"r");
if(!f)
{
printf("ERROR WHILE OPENING THE FILE!!");
exit(0);
} else
{
int d;
fscanf(f,"%d",&(*n));
///we dinamically alocate memory
a = calloc((*n),sizeof(int));
int i=0;
while(!feof(f))
{
fscanf(f,"%d",&a[i++]);
}
}
///if I try to display the values here it works
fclose(f);
return a;
}
void displayValues(int *a,int n)
{
for(int i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
int main()
{
int *a,*b,n,m;
getData(a,&n);
getDataFirstFunction(b,&m);
displayValues(a,n);
displayValues(b,m);
return 0;
}
但是用 void 声明的第一个函数不起作用,我不明白为什么,因为我故意写了一个双指针参数,所以当我分配内存时,当变量打开时它不会丢失在函数完成执行后,编译器会释放堆栈。
第二个名为 getData 的函数确实有意义并且可以工作,但我不知道我是否可以使第一个具有 void 的函数工作,因为似乎内存只分配给堆栈上的变量,然后当它完成执行时在没有为 main 中的指针分配内存的情况下,对内存位置的引用消失了,所以当我尝试在屏幕上显示值时,程序会冻结,然后我什么也得不到。
提前致谢。
【问题讨论】:
-
不要
#include <malloc.h>。它不是 C 标准的一部分(参见例如 n1570...)。请参阅this C reference 网站。阅读编译器的文档(例如GCC,您可以将其调用为gcc -Wall -Wextra -g)。也使用你的调试器(例如GDB...)和valgrind -
这里有很多错误,请在标准模式下调用你的编译器并注意它的诊断,因为它会告诉你问题。运行出现编译错误的代码完全是浪费时间
标签: arrays c dynamic-memory-allocation