Reputation: 21
I made my own strtod()
function.
I can printf
in console but it is giving warning like this when it runs:
myStrTod.c|29|warning: "assignment discards 'const' qualifier from pointer target type"|
#include<stdio.h>
float myStrTod(const char * nPtr, char ** endPtr);
int rakamMi(int c);
int main()
{
float d;
const char *string = "51.2% kabul edildi";
char *stringPtr;
d = myStrTod(string,&stringPtr);
printf("%.3f %s\n",d,stringPtr);
return 0;
}
float myStrTod(const char * nPtr, char ** endPtr)
{
char s1[20],s2[50];
int i,j,k = 0,pnt,y = 1,num1 = 0,num2= 0;
float f1,f2;
for(i = 0; nPtr[i]; i++){
if(rakamMi(nPtr[i]) || nPtr[i] == '.')
s1[i] = nPtr[i];
else break;
}
j = i;
for(; nPtr[i]; i++)
endPtr[i - j] = nPtr + i;
for(i = 0; s1[i]; i++)
if(s1[i] == '.'){
pnt = i;
break;
}
for (i = 0; s1[i]; i++)
{
if(i < pnt) num1 = num1 * 10 + (s1[i] - 48);
else if (i == pnt) continue;
else{
num2 = num2 * 10 + (s1[i] - 48);
++k;
}
}
for(i = 1; i <= k; i++)
y = y * 10;
f1 = num2 / (float) y;
f2 = num1 + f1;
// endPtr = s2;
return f2;
}
int rakamMi(int c)
{
if(c >= 48 && c <= 57)
return 1;
else
return 0;
}
Upvotes: 1
Views: 6408
Reputation: 19385
Program given the result but after that program.exe has stopped working!
The reason for that is this:
j = i;
for(; nPtr[i]; i++)
endPtr[i - j] = nPtr + i;
You're passing the address of just a single char *stringPtr
to the function, but use the parameter endPtr
as if there were an array of char *
, thereby overwriting memory behind the storage of stringPtr
. Change all the above to:
*endPtr = nPtr + i;
Upvotes: 0
Reputation: 30877
You are trying to assign a value of type pointer-to-const-char to a variable of type pointer-to-char. You could change the signature of myStrTod
so that your output is to a pointer to const char:
float myStrTod(const char *nPtr, const char **endPtr);
Then GCC will report a different error:
40937624.c: In function ‘main’:
40937624.c:11:25: warning: passing argument 2 of ‘myStrTod’ from incompatible pointer type [-Wincompatible-pointer-types]
d = myStrTod(string,&stringPtr);
^
40937624.c:2:7: note: expected ‘const char **’ but argument is of type ‘char **’
This can be fixed by declaring stringPtr
as pointer to const:
const char *stringPtr;
Since you never write to the content of *stringPtr
, this is then sufficient.
Upvotes: 1