我是 C 的新手,我必须说你我发现这个指针和引用的东西有点难以理解。我来自 Java,所以这一切都不存在,尽管一旦你习惯了它,有时你会有点迷茫,就像我现在一样。
我有我的头文件:
globals.h
typedef struct {
float *array;
size_t used;
size_t size;
} points;
extern points readedPoints;
而且我的 .c 类具有我想在另一个文件中使用的功能。
graph.c
#include "globals"
points readedPoints;
void readFile( char* filename)
{
...
...
// I read floats from a file and store it in my
// readedPoints. When i print, they are all there
for(i=0; i < readedPoints.used;++i){
//fprintf(stderr, "%d", graphIndices[i]);
fprintf(stderr, " %f\n", readedPoints.array[i]);
}
}
然后在我使用该功能的 .c 中:
init.c
#include "globals.h"
void Init(...){
readFile("graph1.txt");
// here i do that same for-loop to check if 'readedPoints' can be accessed here, but it cant.
for(i=0; i < readedPoints.used;++i){
//fprintf(stderr, "%d", graphIndices[i]);
fprintf(stderr, " %f\n", readedPoints.array[i]);
}
}
我不明白为什么。我将它声明为 extern,它已经在 readFile 函数内的“graph.c”中初始化,但我不能在其他 .c 文件中使用它。请有人解释我为什么以及我做错了什么。非常感谢
编辑。我收到错误:在最后一个 for 循环中访问冲突读取位置
编辑:整个读取功能:
void readFile( char* filename)
{
int i;
int j;
float n;
int nn;
int tags_x;
int nrLines;
int nrColumns;
FILE* fp = fopen( filename, "r" );
if ( fp == NULL )
{
fprintf( stderr, "ERRO na leitura do ficheiro %s\n", filename );
exit( EXIT_FAILURE );
}
/* Read the number of lines */
fscanf( fp, "%d", &nn );
nrLines = nn;
initFPoints(&readedPoints, nrLines*10);
for(i = 0; i < nrLines-2;i++)
{
for(j = 0; j < nrColumns;j++)
{
//printf ("%f ", i);
fscanf (fp, "%f", &n);
//fprintf(stderr, " %f\n", n);
insertFPoints(&readedPoints, n);
}}
fclose( fp );
// here it prints exactly what i want
// for(i=0; i < readedPoints.used;++i){
// //fprintf(stderr, "%d", graphIndices[i]);
// fprintf(stderr, " %f\n", readedPoints.array[i]);
// }
}
void initFPoints(points *a, size_t initialSize) {
a->array = (float *)malloc(initialSize * sizeof(float));
a->used = 0;
a->size = initialSize;
}
void insertFPoints(points *a, float element) {
if (a->used == a->size) {
a->size *= 2;
a->array = (float *)realloc(a->array, a->size * sizeof(float));
}
a->array[a->used++] = element;
}