The following bullet-list the items wrong in your function.
You're incorrectly using
feof()
as the break condition of yourwhile
loop. See this question for more information.You ignore the return result of
fscanf()
and with that thereby have no assurance at all the parameter parsing succeeded or not. See the documentation offscanf()
.Your code does not fit the model of the file content. The file, according to your code, should set
ir
,suly
,csom
, andel
to values0
,0
,7
, and8
respectively. You then allocate space for exactly two pointers-to-int, saving the result inellista
, then proceed to index into*ellista
up toel
items, which is clearly not2
. It is neither clear nor evident that you want a 2xN matrix or an Nx2 matrix when this is finished, and the code as-written does neither correctly.Stylistic, but helpful: You should be setting your out-parameters on success of your function, not on initial entrance or parse. Eg: Your
ellista
by-address parameter should be set as the last operation, not the first, based on the success of the function. Declare a localint** local;
temp var, run your algorithm populating that, and upon success set the out-parameter.
All of that said, I think you want a 2xN matrix, and if so, the code below will do that. Note this does not check the results of the malloc and calloc calls, which i leave to you. This function will return zero (0
) on success, non-zero on failure :
int beolvas_ellista(int *ir, int *suly, int *csom, int *el, int ***ellista, const char *allomany)
{
FILE * f = fopen(allomany,"r");
int ** local = NULL;
int i, res = -1;
if (f == NULL)
return res;
if (fscanf(f,"%d",ir) == 1 &&
fscanf(f, "%d",suly) == 1 &&
fscanf(f,"%d",csom) == 1 &&
fscanf(f,"%d",el) == 1)
{
// allocate two pointers, then in those two pointers, allocate
// space for *el integers.
local = malloc(2 * sizeof(*local));
local[0] = calloc(*el, sizeof(*(local[0])));
local[1] = calloc(*el, sizeof(*(local[0])));
for (i=0; i<*el; ++i)
{
if (fscanf(f, "%d", local[0]+i) != 1 ||
fscanf(f, "%d", local[1]+i) != 1)
break;
}
// only if i == *el did we finish the above
if (i == *el)
{
*ellista = local;
res = 0;
}
else
{ // failed to read file content. free up memory
// and return error state.
free(local[0]);
free(local[1]);
free(local);
}
}
fclose(f);
return res;
}