Reputation: 1
i've looked through quite a few questions of 2-d malloc'd arrays already but bascially for whatever reason i cannot find a solution.... my google fu sux sorry =(. been using the site all day for syntactual help though thanks to everyone who helps here! =)
anyways i cant seem to get this fscanf to work =/ if someone could help me it would be much appreciated because i cant see any error at all but i know there is one because it is at this point that my program crashes.
array1 = (int**)malloc((c)*sizeof(int*));
int a = 0, i = 0;
for (a = 0; a < c; a++){
array1[a] = (int*)malloc((c+1)*sizeof(int));
}
a=0;
for(a = 0; a < c; a++){
for(i = 0; i < c; i++){
fscanf(ifp, "%d", array1[a][i]);
}
}
where c is the maximum size of the array needed. in this case it is set to 3 but i do need it as a variable
Upvotes: 0
Views: 236
Reputation: 1749
malloc and other syntext is correct, the issue is in reading the value to array
replace this
fscanf(ifp, "%d", array1[a][i]);
with
fscanf(ifp, "%d", &array1[a][i]);
Always enable complier warning, and pay heed to it:)
Upvotes: 1
Reputation: 87486
fscanf takes pointers, so I would think you need to prepend its third argument with an ampersand. Didn't the compiler warn you about that?
Upvotes: 1
Reputation: 409356
When using the scanf
family of function to read a value, the destination needs to be a pointer. array1[a][i]
is not a pointer, it an actual value (which scanf
will treat as a pointer and you now entered the territory of undefined behavior).
What you want is &array1[a][i]
.
PS.
You should not cast the returned value of malloc
.
Upvotes: 5