问题
I am reading numbers from a file.When I try to put each number into an double dimensional array it gives me below error.How do I get rid of this message? My variables: FILE *fp; char line[80];
Error: Cast from char * to int loses precision
Code:-
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char line[80],*pch;
int points[1000][10];
int centroid[1000][10];
float distance[1000][10];
int noofpts=0,noofvar=0,noofcentroids=0;
int i=0,j=0,k;
fp=fopen("kmeans.dat","r");
while(fgets(line,80,fp)!=NULL)
{
j=0;
pch=strtok(line,",");
while(pch!=NULL)
{
points[i][j]=(int)pch;
pch=strtok(NULL,",");
noofvar++;
j++;
}
noofpts++;
i++;
}
noofvar=noofvar/noofpts;
printf("No of points-%d\n",noofpts);
printf("No of variables-%d\n",noofvar);
return 0;
}
回答1:
This is the offending line:
points[i][j]=(int)pch;
You should replace it with
points[i][j]=atoi(pch);
atoi is a function that converts a C string representing an integer number in decimal representation to an int
.
回答2:
This error occurs while compiling on a 64 bit machine
but may not occur on a 32 bit machine
as there is difference in size for char*
and int
.
on 64 bit sizeof(char*)
is 8 and sizeof(int)
is 4
on 32 bit sizeof(char*)
is 4 and sizeof(int)
is 4
来源:https://stackoverflow.com/questions/12417378/cast-from-char-to-int-loses-precision