Arrays 为什么不将内存分配给阵列?
在大学里,我被要求用C语言构建一个函数,从文件中读取大量值,然后使用指针(它必须使用指针)将内存动态分配给引用传递的数组,然后我们被要求使用另一个函数显示读取的值。Arrays 为什么不将内存分配给阵列?,arrays,c,dynamic-memory-allocation,Arrays,C,Dynamic Memory Allocation,在大学里,我被要求用C语言构建一个函数,从文件中读取大量值,然后使用指针(它必须使用指针)将内存动态分配给引用传递的数组,然后我们被要求使用另一个函数显示读取的值。 我在这里展示了两种方法: #include <stdio.h> #include <stdlib.h> #include <malloc.h> ///Read an 1d array from the file stuff.txt inside of a
我在这里展示了两种方法:
#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;
}
#包括
#包括
#包括
///从函数内部的stuff.txt文件中读取1d数组
///并自动分配内存
///然后在屏幕上显示从文件读取的值
void getDataFirstFunction(int**a,int*n)
{
文件*f;
f=fopen(“stuff.txt”、“r”);
如果(!f)
{
printf(“打开文件时出错!!”;
出口(0);
}否则
{
int d;
fscanf(f、%d、&(*n));
///我们友好地分享记忆
a=calloc((*n),sizeof(int));
int i=0;
而(!feof(f))
{
fscanf(f、%d、&a[i++]);
}
}
///如果我尝试在这里显示值,它会起作用
///但当我试图阅读时,在显示器上显示它们
///功能它不再工作了
fclose(f);
}
int*getData(int**a,int*n)
{
文件*f;
f=fopen(“stuff.txt”、“r”);
如果(!f)
{
printf(“打开文件时出错!!”;
出口(0);
}否则
{
int d;
fscanf(f、%d、&(*n));
///我们友好地分享记忆
a=calloc((*n),sizeof(int));
int i=0;
而(!feof(f))
{
fscanf(f、%d、&a[i++]);
}
}
///如果我尝试在这里显示值,它会起作用
fclose(f);
返回a;
}
无效显示值(int*a,int n)
{
对于(int i=0;i函数内部,a
是指向指针的指针的副本。
在这里,您为该副本分配了其他内容:
a = calloc((*n),sizeof(int));
这在功能之外没有任何影响
在函数之外,a
是指向int的指针,在那里写一个指向int的指针是有意义的。
您可以这样做(通过函数中使用的副本),例如
*a = calloc((*n),sizeof(int));
对于函数之外的效果,应该使用指向int的指针地址调用
getData(&a,&n);
使用此int*getData(int**a,int*n)
可以将返回的int指针分配给函数外部的a
。但是不要在这里getData(a,&n);
。对于返回指向int的指针,此行不适合返回一个;
,因为它返回指向int的指针。该指针确实包含正确的值(新分配的指向int的指针),但按类型来说仍然不正确
注:
您非常依赖您的fscanf()
s工作,因此用于大小的n
可能未初始化…
当(!feof(f))
,而且
d
在函数内部似乎没有使用过…因此,请注意M.M.关于阅读编译器警告的评论中的建议。不要
#包括。它不是C标准的一部分(参见例如…)。参见网站。阅读编译器的文档(例如,您可以将其作为gcc-Wall-Wextra-g
)调用。还可以使用调试器(例如…)这里有很多错误,请在标准模式下调用编译器,并注意它的诊断,因为它会告诉您有关问题。运行导致编译错误的代码完全是浪费时间