I am trying to understand why the following code does not work... please help:
void incme(double *p)
{
printf("%x,%x\n",p,*p);
*p = *p + 1;
printf("%x,%x\n",p,*p);
}
int main()
{
int i = 1;
incme((double *)&i);
printf("%x,%x",&i,i);
}
the output is:
ff99a348,1
ff99a348,1
ff99a348,1
I am expecting:
ff99a348,1
ff99a348,2
ff99a348,2
it breaks everything I know about pointers...
Thanks.
EDIT:
the main question i am asking the the type cast in incme((double *)&i); why isit not casting it to double and pass it to the function ? ... sorry for not pointing out eailer ....
Because of undefined behavior. Integers are not floating point, and floating point is not integers. Besides that, I think you will find that sizeof(int) != sizeof(double).
You're also breaking the strict aliasing rule.
Unrelated to your question, you should use the "%p" format if you want to print pointers.
When you do *p = *p + 1; with p beeing a double* there is a lot going under the hood, indeed, double are represented using a custom format (wiki), when you use printf to display it as a integer after that, the internal representation of the memory at this address has changed (to a double representation), this is why you obtain such a result.
I ran the code and obtained the following output:
205afc2c,205afd28
205afc2c,593b4ab0
205afc2c,0
It shows use that the value is invalid as a double, and when it's incremented, it does not update the sizeof(int) first bits of the double (as it print 0 in the last line).
Hope I made myself clear !
Edit
I changed the code a little to show you what actually happen:
void incme(double *p)
{
printf("%x,%lf\n",p,*p);
*p = *p + 1;
printf("%x,%lf\n",p,*p);
}
int main()
{
int i = 1;
incme((double *)&i);
printf("%x, %lf, %d",&i,i, i);
}
Gives me the following output:
cb90990c,0.000000
cb90990c,1.000000
cb90990c, 1.000000, 0
As you can see, if you print them as double, the value is indeed correct (but the binary representation of 1.0000 is not 00000000001 as I said previously, this is why the hex formatting gives you a large number).
Back in the main, if you display the value as a double (event if i is supposed to be a int) as the incme function changed the memory layout of it, it does print 1.0000, but the first 32bits of the memory at this address are 0 hence, printing it as an int gives you 0.
The main reason, the printf statements should read -
printf( "%p,%f", p, *p );
This will show your increment of the double.
Also - as stated, an int is generally 4 bytes and a double uses 8 bytes. (on most systems)
Related
I wrote a program which returns a determinant of a matrix. I have a problem, actually; it always returns the "0" value. I notice that my determinant always stays as 0 even though I add numbers to it.
I wrote an English translation in the comments to understand my program better. I use a method in which we select one number and then crossed the element from the column and line of the selected number and then calculate the determinant of the uncrossed elements.
#include<stdio.h>
#include<stdlib.h>
float wznmacierz(float*macierz, int rozmiar)/*"macierz" means a matrix and "rozmiar" is a size of matrix */
{
if (rozmiar == 1)
return *macierz;
float *podmacierz = malloc((rozmiar-1)*(rozmiar-1)*sizeof(float)); // making a second matrix for uncrossed elements.
int wyznacznik = 0; // wyznacznik is the determinant of matrix
for(int element_S = 0; element_S <rozmiar; element_S++) //element s is a number from first line
{
for (int w = 1 ; w < rozmiar; w++ ) //line of checking element
{
for(int kolumna = 0; kolumna < rozmiar; kolumna++)//column of chcecking element
{
if(kolumna == element_S)
continue;
*podmacierz = macierz[(rozmiar*w)+(kolumna)];
podmacierz++;
}
}
wyznacznik += macierz[element_S]*( element_S % 2 ? -1: 1)* wznmacierz(podmacierz, rozmiar-1);
}
return wyznacznik;
}
void main()
{
float a[2][2]={{1,3},{9,8}};
printf("%d", wznmacierz(a,2));
}
Change void main to int main, because main returns an int.
In printf("%d", wznmacierz(a,2)); , change %d to %g, because %d is for formatting an int, but wznmacierz returns a float. %g will format a float. Also add \n after %g to complete the line being output.
In printf("%d", wznmacierz(a,2));, change a to *a because wzmacierz expects a pointer to a float, not a pointer to an array of float. This is a kludge to get your program “working” quickly; see Notes below.
You cannot use podmacierz both to hold the start address of the allocated array and to increment to places within the array. Inside the loop on element_S, put float *p = podmacierz; to make a second pointer, and change the uses of podmacierz inside that loop to p.
Before returning from the function, use free(podmacierz); to release the allocated space.
Notes
In main, a is declared as float a[2][2]. This makes it an array of 2 arrays of 2 float. In the call wznmacierz(a,2), a is automatically converted to a pointer to its first element. That produces a pointer to an array of 2 float. However, wznmacierz is declared with a parameter float*macierz, which is a pointer to a float.
One way to fix this is to pass *a. Once a is converted to a pointer to its first element, a pointer to an array of float, then applying * produces the thing that pointer points to, an array of float. Then that array of float is automatically converted to a pointer to its first element, producing a pointer to a float. You could also write wznmacierz(&a[0][0], 2).
This produces a pointer of the correct type for wznmacierz, which then access the array by calculating element locations, using macierz[(rozmiar*w)+(kolumna)]. This nominally calculates correct addresses for the array elements, since arrays are laid out in memory contiguously, but it is bad style unless necessary, and some people might consider it not to conform to the C standard in a pedantic sense.
One fix would be to define a in main as float a[2*2] = {1, 3, 9, 8};. Then the matrix is implemented as single flat array of float everywhere it is used.
Another fix would be to upgrade wznmarcierz to use two-dimensional arrays. A number of changes are needed to do this. I have not tested them, but I think they are at least:
Change wznmacierz(a,2) to wznmacierz(2, a).
Change the declaration of wznmacierz to float wznmacierz(int rozmiar, float macierz[rozmiar][rozmiar]).
Change the use of macierz inside the function from macierz[(rozmiar*w)+(kolumna)] to macierz[w][kolumna].
Change float *podmacierz = malloc((rozmiar-1)*(rozmiar-1)*sizeof(float)); to float (*podmacierz)[rozmiar-1] = malloc((rozmiar-1) * sizeof *podmacierz);.
Remove the float *p = podmaciarz; that I told you to insert above.
Inside the loop using w, insert float *p = podmacierz[w];.
Change macierz[element_S] to macierz[0][element_S].
Change wznmacierz(podmacierz, rozmiar-1) to wznmacierz(rozmiar-1, podmacierz).
#include <stdio.h>
void print_binary(int n);
void test();
int main(){
test();
return 0;
}
void print_binary (int n){
unsigned int mask = 0;
mask = ~mask^(~mask >> 1);
for (; mask != 0; mask >>= 1){
putchar ((n & mask) ? '1' : '0');
}
}
void test(){
int x;
float *p;
p = (float *) &x;
printf ("x init value :%d\n", x);
printf ("addr x and p are %p %p\n", &x, p);
printf ("print x in bit ");
print_binary(x);
printf ("\n");//00000000000000000000000000000000
*p = 6.35;
printf ("print x in bit ");
print_binary(x);
printf ("\n");//01000000110010110011001100110011
printf ("x after 6.35 value :%d\n", x);//1087058739
printf ("call1 x:%.100f\n", x);//0.0000000.....
printf ("x:%d\n", x);//1087058739
printf ("call2 x:%f\n", x);//0.000000
printf ("p:%f\n", *p);//6.350000
printf ("call3 x:%f\n", x);//6.350000
}
Results:
x init value :0
addr x and p are 0x7ffc37d5ba8c 0x7ffc37d5ba8c
print x in bit 00000000000000000000000000000000
print x in bit 01000000110010110011001100110011
x after 6.35 value :1087058739
call1 x:0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
x:1087058739
call2 x:0.000000
p:6.350000
call3 x:6.350000
I print my x after *p = 6.35;, and
in the memory, we get 01000000110010110011001100110011, this is the right number according to the IEEE754,
could someone explain why my first printf ("call1 x:%.100f\n", x) print me 0.00...,
but after I printf ("p:%f\n", *p), it can print the 6.35 ?
Dereferencing p is undefined behavior, since p is not pointing to a float, but to an int (ref. eg. What is the strict aliasing rule?).
Also, trying to print an int with the "%f" format specifier is undefined behavior, since that format specifier expects a double (ref. eg. Why does printf("%f",0); give undefined behavior?).
So, you can't rely on any behavior of this code - anything is possible.
In practice, what's probably happening, is that the compiler decided to move *p = 6.35; to right before printf ("p:%f\n", *p);.
From your tags (type-conversion and implicit conversion) you seem to expect some type conversion to happen.
This is not the case.
Accessing memory with ill-typed pointer does not trigger any conversion to happen. It simply interpretes the memory in a different way. This includes violating the strict aliasing rules causing undefined behaviour.
And when you use
printf ("call1 x:%.100f\n", x);//0.0000000.....
you are cheating your compiler.
You promise to pass a double value (%f format specifier) which typically holds 8 bytes but then you only pass 4 bytes of an integer.
Mismatch in type specifier and parameter type causes undefined bahaviour and all expectations are worhless.
Then again you use
printf ("p:%f\n", *p);//6.350000
which works fine as you provide the proper double parameter. (here is the only implicit type conversion)
Your compiler should print some warnings when you try to compile this code.
And you should always listen to the compiler and resolve the warnings.
Okay this is actually a very simple code but since I am only starting to learn C, please be patient and help me out. I'll be putting my Questions as comments beside the code so that it easy to relate to which part of the code I have a doubt.
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",output_no);
/*here I wanted to print only the integer part of the output_no */
}
The problem with this is that I had a book and it displayed the value for third no as 0.
And then in another program it says that compile time error is shown.
Second program:
#include <stdio.h>
void main()
{
int x = 5.3%2;
printf("Value of x is %d", x);
}
For this program, the book says that a compile time error will be shown. I fail to understand why that is the case. According to me the output should be 1.
If I were to use the following code instead of the previous code:
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",dec_no);
}
What output should I expect? Do I still get a zero or some unpredictable output?
The problems with using just
printf("Third No:%d\n",output_no);
is that:
output_no gets converted to a double before being passed to printf.
When printf sees %d as the format specifier, it expects an int. When the object being passed is of type double, the behavior is undefined.
When you want to print a truncated integral value of a floating point number, you can do one of the following.
Create a temporary variable of the integral type and assign to it the floating point number.
int temp = output_no;
printf("Third No:%d\n", temp);
Explicitly cast the floating point number to an integral type.
printf("Third No:%d\n", (int)output_no);
printf("Third No:%d\n",dec_no);
What output should I expect? Do I
still get a zero or some unpredictable output?
As of the printf function is concerned,
When you try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
But it is possible to use %c to print the character equivalent of the integer value. Also using of %d to print ASCII value (integer representations) of character is acceptable.
Second program: For this program, the book says that a compile time
error will be shown.
According to C Reference manual
7.3.3 expression % expression
The binary % operator yields the remainder from the division of the first expression by the second. Both operands must be int or char, and
the result is int. In the current implementation, the remainder has
the same sign as the dividend.
Here in your case you are providing one value 5.3 so it is neither char nor int so that is why it generates compilation error.
If you still want to run that program you can do that by using fmod() function.
Try this code :
#include<stdio.h>
#include<math.h>
void main()
{
float x=5.3;
int c =2;
printf("Value of xremainer is %lf",fmod(x,c));
}
Compile it as :
$gcc test.c -lm
This is not homework, but my last assignment made it clear that I didn't clearly understand pointers when coding C.
Therefore, I tried to type a simple program using pointers just to invert an integer in a function, so I could figure out where the gap in my understanding is.
Apparently, I've arrived at it, but I still cannot figure out what I am doing wrong.
My source code is below.
#include <stdio.h>
float invert(int *num);
void main (void)
{
int num;
float a;
printf("enter an integer \n");
scanf("%i", &num);
printf("Number entered %i \n", num);
a=invert(&num);
printf("This is the invse from main %f \n", a);
}
float invert(int *num) /* function inverts integer */
{
float invse;
printf("num is %i \n\n", *num);
invse = 1/(float)num;
printf("invse is %f \n\n", invse);
return(invse);
}
My thinking was that I used the pointer to direct the computer to use the value stored at the address for num in the function invert(). The pointer appears in the variable declaration. I cast the value stored at that pointer as a float, so I could invert it, and store it in a local variable.
The problem appears to be in the local variable assignment. My compiler returns "invert.c:29:2: error: pointer value used where a floating point value was expected
invse = 1/(float)num;
^
Apparently my code indicates a pointer value for inverse, but I declared it as a float, which I find confusing.
Any help is appreciated. This will save me on completing my larger set of code for my assignment, which I did not post here.
Thanks.
Judging by the printf call inside invert
printf("num is %i \n\n", *num);
you already know that in order to access the value passed to invert for inversion you have to dereference num pointer: *num.
If so, then why aren't you dereferencing num when you perform the inversion itself?
invse = 1/(float)num;
I mean, if you are the one who wrote that printf, you should also realize that the actual inversion should be done as
invse = 1 / (float) *num;
or, alternatively, as
invse = 1.f / *num;
On top of being incorrect your original variant is illegal: you are not allowed to convert pointers to floating-point types in C, which is the reason for the error message.
P.S. From the bigger picture point of view, there's no real reason to pass that the number to invert by pointer. Passing the immediate value would make more sense
float invert(int num)
{
...
In that case you, of course, don't have to dereference anything inside invert.
today,I write some code to test unsigned int.
#include <stdio.h>
int sum_element(float ele[], unsigned int len);
int main(void){
float ele[] = {1.1,2.2,3.3};
float sum = sum_element(ele,3);
printf("sum is %f\n",sum);
return 0;
}
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f, i=%d\n",sum,i);
sum += ele[i];
}
return sum;
}
in this example, i have a mistake, the type of variable sum, should be float, but i write int, the compile command:
gcc test.c -o test
and i run this code
./test
the output of the function sum_element is:
sum=0.000000, i=1
sum=0.000000, i=1
sum=0.000000, i=1
and then i found the mistakes, and i change the type of sum to float, then compiled again,
and when i run it, the output is :
sum=0.000000, i=0
sum=1.100000, i=1
sum=3.300000, i=2
this time, the output like normal,but in first output, why the variable of i is always the same value of 1, can someone tell me?
Nothing to see. You invoked undefined behavior by passing the wrong type to printf, so all output of the program is meaningless. The %f format specifier requires an argument of type double (by the way, float would automatically promote to double in this context, so float would be okay too), but you passed it an argument of type int.
You have to understand how va_arg work. Printf is a function that take a undefined number of arguments. The problem is that those arguments are not typed.
When you specify int, double, ect... the compiler assign differente number of bytes (in a specific order) depending on the arguments. So when you call a function that has type argument, the function know how it should read those bytes.
Here it cannot know since it isn't type. So the printf function is going to believe what you give it. If you ask for example for a 4 bytes when you real value is 8 bytes, the function will read the first 4 bytes believing it the value you ask for. But then the next value you try to match will start with the next 4 bytes. Wich will give you garbage.
You can try to do 2 printf, and you will see that the value of i is actually the good one. Only the way to read it was wrong.
int sum_element(float ele[], unsigned int len){
int sum=0.0; //mistake,should be : float sum = 0.0
int i=0;
for(i=0;i<= len-1;i++){
printf("sum=%f\n",sum);
printf("i=%d\n",i);
}
return sum;
}
Hope this can help.
EDIT:
Maybe a example is easier to understand. Try this function:
int sum_element(float ele[], unsigned int len){
int sum=24222.55455555; //mistake,should be : float sum = 0.0
char c = 0 ;
for(i=0;i<= len-1;i++){
printf("sum=%f, n= %d n2 = %d\n",sum,i,c);
}
return sum;
}
You should get a interesting value for n2.
I think the answer is that in the first case, the value being printed is not that of i at all. Two parameters are passed to printf which then reads two off. Those passed in are two ints, and then a double and and int are read off. Because the double is read off the stack first, when the int is read it is not from where the value of i was passed, hence the bogus value. Most likely the double covers enough of the stack to include both the passed ints.
Of course, results may vary, being undefined.