#include <stdio.h>
#include <stdlib.h>
#include <cstring>
int main()
{
int size = 5 ;
int* c = (int*)calloc(size,sizeof(int));
memset(c,0,size*sizeof(int)); // when I input 1 or another value it doesn't work
for (int i=0; i<size;i++){
printf("values %d\n", c[i]);
}
free(c);
}
This program's output in the below;
value 0
value 0
value 0
value 0
value 0
But if I change 0 value to 1:
value 16843009
value 16843009
value 16843009
value 16843009
value 16843009
I seperated the memory using calloc. I want to assign a value to this memory address that I have allocated with the memset function. When I give the value 0 here, the assignment is done successfully. I am displaying a random value instead of the values I gave outside of this value. How can I successfully perform this assignment using the memset function?
The memset function sets each byte in the given memory segment to the given value. So you're not setting each int to 1, but each byte in each int to 1.
The decimal number 16843009 in hex is 0x01010101, which illustrates that this is exactly what happens.
If you want to set each int to a non-zero value, you'll need to do it in a loop.
memset operates on bytes. It sets every byte to 1 rather than every 4-byte int. When you interpret the results as ints you get 0x01010101 in hex, which is 16843009 in decimal.
Related
I'm trying to swap two floats using pointers ,
My code :
#include <stdio.h>
void swap(float* p, float* q);
int main() {
double num1,num2;
printf("Please write 2 numbers ");
scanf("%lf %lf",&num1 , &num2);
swap(&num1,&num2);
printf("\nnum1 is : %.2lf \n",num1);
printf("num2 is : %.2lf \n",num2);
return 0;
}
void swap(float* p, float* q){
float a;
a=*p;
*p=*q;
*q=a;
}
My issues :
The code doesn't swap
The pointers in the swap function show value 0 for the pointer of the address I'm sending .
For example - input 99 22 -> gives me 0 :
Using Debugger I get
I don't get why I'm getting that , if according to this comment I have an address
that I sent (let's assume I sent 00001 ) then a pointer to that address would be my value (99 in this example ) but I get 0 ...
I'd appreciate any help !
As pointed out by comments, the problem is that your swap function takes float pointers while you are using double variables.
Since float type is used to describe floating point value over 4 bytes (32 bits) and the double type describes floating point value over 8 bytes (64 bits), when you pass double pointers to a function that treat them as float type, the values are wrongly assigned (over 4 bytes instead of 8 bytes) from one memory area to another.
The half of bits of a double does not make a valid corresponding float.
#include<stdio.h>
int main(){
int a1[]={6,7,8,18,34,67};
int a2[]={23,56,28,24};
int a3[]={-12,27,-31};
int *y[]={a1,a2,a3};
int **a= y;
printf("%d\n",a[0][2]);
printf("%d\n",*a[2]);
printf("%d\n",*(++a[0]));
printf("%d\n",*(++a)[0]);
printf("%d\n",a[-1][1]);
return 0;
}
When I run the above code output is 8,-12,7,23,8. But if i change the last 3 lines to
printf("%d\n",*(++a[2]));
printf("%d\n",*(++a)[1]);
printf("%d\n",a[-1][1]);
output is 8,-12,27,27,7. I'm unable to understand last printf statement. How does a[-1][something] is calculated ? And according to me *(++a)[1] should print 56 instead of 27 !
Pointers and array bases are in fact addresses in virtual memory. In C, they can be calculated into new addresses. Since the compiler knows the size of memory the pointer points to (e.g. int * points to 4 Bytes), a pointer +/- 1 means the address +/- the size (e.g. 4 Bytes for int).
The operator * means to get the value stored in the specified address.
Another trick here is the priorities of the operators. [] is calculated before ++.
If you understand what I mean above, your problem should be resolved.
according to me *(++a)[1] should print 56 instead of 27 !
++a increments a to the next int *, so after it pointed to y[0] equal to a1, it points to y[1] equal to a2. Then [1] in turn designates the next int * after y[1], i. e. y[2] equal to a3+1 (due to the preceding ++a[2]). Lastly, * designates the int which y[2] points to, i. e. a3[1] equal to 27.
This question already has answers here:
Mystery with bool data type
(3 answers)
Closed 7 years ago.
(Also see Mystery with bool data type for a similar question with relevant answers.)
While debugging a program, I noticed strange output when printing an uninitialized bool array as integers. Consider this C program:
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 30;
bool* bools = malloc(n * sizeof(bool)); // Uninitialized memory.
for (int i=0; i<n; ++i)
{
int x = bools[i];
assert(x == 0 || x == 1);
printf("%d ", x);
}
printf("\n");
free(bools);
}
Due to the uninitialized bool array, the output varies with each run based on previous memory contents, of course. My understanding is that casting a bool to an int should always produce either 0 or 1 (see the assertion above, which always passes); however, I frequently see output like this:
0 0 0 0 0 0 0 144 0 0 0 0 0 0 0 144 16 0 92 113 255 127 0 0 160 41 222 134 255 127
Can someone explain how this program can print anything besides 0s and 1s?
Update: The short answer is that casting an uninitialized bool to int can produce values besides 0 and 1. (In my case, bools are stored as bytes, so their uninitialized values can be anything in [0..255].) Also, the assert line above seems to be optimized out, which made this problem more difficult to debug.
To provide a little more context: I was originally writing a function to count the number of set bits in a bool array, e.g.:
int popcount(const bool* v, int n)
{
int c=0;
for (int i=0; i<n; ++i) c += v[i];
return c;
}
I noticed that sometimes this would return a result greater than n, which seemed impossible. The problem was that the bool array was uninitialized. Zeroing the array fixed the problem, but it still doesn't make sense to me how casting a bool to an int could produce something besides 0 or 1.
Because it doesn't make sense to restrict boolean read operations to clamp the actual value to either 0 or 1.
The value of an undefined variable can be anything that fits within the variable's size. A bool usually occupies a single byte (because that's the smallest addressable unit), and on systems with 8-bit bytes it means a bool can store 256 different values. That's why the numbers you're seeing range from 0 to 255.
The implementation is free to assume that you will not invoke UB, that's why you're seeing values besides 0 and 1. In code without UB, all bools would convert to either 0 or 1.
A bool (_Bool) object can only hold values 0 or 1. In your case your program invokes undefined behavior as you are accessing uninitialized memory returned by malloc which has indeterminate value.
A strictly conforming program will only evaluate _Bool objects to 0 or 1.
So I have a program in C. its running but I don't understand how the output is generated ??
Here is the program :
#include <stdio.h>
int c;
void main() {
int a=10,b=20,j;
c=30;
int *p[3];
p[0]=&a;
p[1]=&b;
p[2]=&c;
j=p[0]-p[2];
printf("\nValue of p[0] = %u\nValue of p[2] = %u\nValue of j = %d\n\n",p[0],p[2],j);
}
and Here is the output :
Value of p[0] = 3213675396
Value of p[2] = 134520860
Value of j = -303953190
Can anyone tell me how j got this value i.e. -303953190 ?? It is supposed to be 3079154536
You are doing 3213675396 - 134520860. If you want to get the value use *p[0]. If your intention is to substract the address(which doesnt make sense but still) the expected answer should be 3079154536. But since the number if too large to hold hence you get the answer -303953190. Consider char for simplicity on number line
-128 -127 -126 -125 ... 0 1 2 ... 125 126 127
Now if you try to store 128 it out of range so it will give value -128. If try to assign value 130 you will get -126. So when the right hand side limit is exceeded you can see the counting starts from the left hand side. This is just for explanation purpose only the real reason for this behavior is owed due the fact that it is stored as two's compliment. More info can be found here
You should compute the difference of the pointed objects rather than of the pointers:
j=(*(p[0]))-(*(p[2]));
p is array of pointers to int - so its storing pointers to int and not ints. Hence, p[0] and p[2] are pointers - subtracting them will give you an integer which may overflow that you are trying to store in an int where the problem lies. Also addresses are to printed using %p not %d.
Dereference the value and you will get what you are looking for, like this:
j=p[0][0]-p[2][0];
or like this:
j=*(p[0])-*(p[2]);
Substracting two pointers results in a signed integer.
From the C Standard chapter 6.56:
6.5.6 Additive operators
[...]
9 When two pointers are subtracted, both shall point to elements of the same array object,
or one past the last element of the array object; the result is the difference of the
subscripts of the two array elements. The size of the result is implementation-defined,
and its type (a signed integer type) is ptrdiff_t defined in the < stddef.h> header.
And assigning the pointer difference to an int overflows the int.
To get around this overflow instead of
int j;
use
ptrdiff_t j;
and then print the value using %td.
From the C Standard chapter 7.17:
7.17 Common definitions < stddef.h>
[...]
2 The types are
ptrdiff_t
which is the signed integer type of the result of subtracting two pointers;
Also (unrelated)
void main()
is wrong. It shall be
int main(void)
So the correct code would look like this:
#include <stdio.h>
#include <stddef.h> /* for ptrdiff_t */
int c;
int main(void)
{
int a=10, b=20;
ptrdiff_t j;
int * p[3];
c=30;
p[0]=&a;
p[1]=&b;
p[2]=&c;
j=p[0]-p[2];
printf("\nValue of p[0] = %p\nValue of p[2] = %p\nValue of j = %td\n\n",
(void *) p[0],
(void *) p[2],
j);
return 0;
}
You're printing it as an integer instead of an unsigned. Use %u instead of %d.
Try this:
#include <stdio.h>
int c;
void main() {
int a=10,b=20;
unsigned j;
c=30;
int *p[3];
p[0]=&a;
p[1]=&b;
p[2]=&c;
j=(unsigned)p[0]-(unsigned)p[2];
printf("\nValue of p[0] = %u\nValue of p[2] = %u\nValue of j = %u\n\n",(unsigned)p[0],(unsigned)p[2],j);
}
The output of the following c program is: 0.000000
Is there a logic behind the output or is the answer compiler dependent or I am just getting a garbage value?
#include<stdio.h>
int main()
{
int x=10;
printf("%f", x);
return 0;
}
PS:- I know that to try to print an integer value using %f is stupid. I am just asking this from a theoretical point of view.
From the latest C11 draft — §7.16 Variable arguments <stdarg.h>:
§7.16.1.1/2
...if type is not compatible with the type of the actual next argument
(as promoted according to the default argument promotions), the behavior
is undefined, except for the following cases:
— one type is a signed integer type, the other type is the corresponding
unsigned integer type, and the value is representable in both types;
— one type is pointer to void and the other is a pointer to a character type.
The most important thing to remember is that, as chris points out, the behavior is undefined. If this were in a real program, the only sensible thing to do would be to fix the code.
On the other hand, looking at the behavior of code whose behavior is not defined by the language standard can be instructive (as long as you're careful not to generalize the behavior too much).
printf's "%f" format expects an argument of type double, and prints it in decimal form with no exponent. Very small values will be printed as 0.000000.
When you do this:
int x=10;
printf("%f", x);
we can explain the visible behavior given a few assumptions about the platform you're on:
int is 4 bytes
double is 8 bytes
int and double arguments are passed to printf using the same mechanism, probably on the stack
So the call will (plausibly) push the int value 10 onto the stack as a 4-byte quantity, and printf will grab 8 bytes of data off the stack and treat it as the representation of a double. 4 bytes will be the representation of 10 (in hex, 0x0000000a); the other 4 bytes will be garbage, quite likely zero. The garbage could be either the high-order or low-order 4 bytes of the 8-byte quantity. (Or anything else; remember that the behavior is undefined.)
Here's a demo program I just threw together. Rather than abusing printf, it copies the representation of an int object into a double object using memcpy().
#include <stdio.h>
#include <string.h>
void print_hex(char *name, void *addr, size_t size) {
unsigned char *buf = addr;
printf("%s = ", name);
for (int i = 0; i < size; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
}
int main(void) {
int i = 10;
double x = 0.0;
print_hex("i (set to 10)", &i, sizeof i);
print_hex("x (set to 0.0)", &x, sizeof x);
memcpy(&x, &i, sizeof (int));
print_hex("x (copied from i)", &x, sizeof x);
printf("x (%%f format) = %f\n", x);
printf("x (%%g format) = %g\n", x);
return 0;
}
The output on my x86 system is:
i (set to 10) = 0a000000
x (set to 0.0) = 0000000000000000
x (copied from i) = 0a00000000000000
x (%f format) = 0.000000
x (%g format) = 4.94066e-323
As you can see, the value of the double is very small (you can consult a reference on the IEEE floating-point format for the details), close enough to zero that "%f" prints it as 0.000000.
Let me emphasize once again that the behavior is undefined, which means specifically that the language standard "imposes no requirements" on the program's behavior. Variations in byte order, in floating-point representation, and in argument-passing conventions can dramatically change the results. Even compiler optimization can affect it; compilers are permitted to assume that a program's behavior is well defined, and to perform transformations based on that assumption.
So please feel free to ignore everything I've written here (other than the first and last paragraphs).
Because an integer 10 in binary looks like this:
00000000 00000000 00000000 00001010
All printf does is take the in-memory representation and try to present it as an IEEE 754 floating point number.
There are three parts to a floating point number (from MSB to LSB):
The sign: 1 bit
The exponent: 8 bits
The mantissa: 23 bits
Since an integer 10 is just 1010 in the mantissa bits, its a very tiny number that is much less than the default precision of printf's floating point format.
The result is not defined.
I am just asking this from a theoretical point of view.
The complete chris's excellent answer:
What happens in your printf is undefined, but it could be quite similar to the code below (it depends on the actual implementation of the varargs, IIRC).
Disclaimer: The following is more "as-if-it-worked-that-way" explanation of what could happen in an undefined behaviour case on one platform than a true/valid description that always happens on all platforms.
Define "undefined" ?
Imagine the following code:
int main()
{
int i = 10 ;
void * pi = &i ;
double * pf = (double *) pi ; /* oranges are apples ! */
double f = *pf ;
/* what is the value inside f ? */
return 0;
}
Here, as your pointer to double (i.e. pf) points to an address hosting an integer value (i.e. i), what you'll get is undefined, and most probably garbage.
I want to see what's inside that memory !
If you really want to see what's possibly behind that garbage (when debugging on some platforms), try the following code where we will use an union to simulate a piece of memory where we will write either double or int data:
typedef union
{
char c[8] ; /* char is expected to be 1-byte wide */
double f ; /* double is expected to be 8-bytes wide */
int i ; /* int is expected to be 4-byte wide */
} MyUnion ;
The f and i field are used to set the value, and the c field is used to look at (or modify) the memory, byte by byte.
void printMyUnion(MyUnion * p)
{
printf("[%i %i %i %i %i %i %i %i]\n"
, p->c[0], p->c[1], p->c[2], p->c[3], p->c[4], p->c[5], p->c[6], p->c[7]) ;
}
the function above will print the memory layout, byte by byte.
The function below will prinf the memory layout of different types of values:
int main()
{
/* this will zero all the fields in the union */
memset(myUnion.c, 0, 8 * sizeof(char)) ;
printMyUnion(&myUnion) ; /* this should print only zeroes */
/* eg. [0 0 0 0 0 0 0 0] */
memset(myUnion.c, 0, 8 * sizeof(char)) ;
myUnion.i = 10 ;
printMyUnion(&myUnion) ; /* the representation of the int 10 in the union */
/* eg. [10 0 0 0 0 0 0 0] */
memset(myUnion.c, 0, 8 * sizeof(char)) ;
myUnion.f = 10 ;
printMyUnion(&myUnion) ; /* the representation of the double 10 in the union */
/* eg. [0 0 0 0 0 0 36 64] */
memset(myUnion.c, 0, 8 * sizeof(char)) ;
myUnion.f = 3.1415 ;
printMyUnion(&myUnion) ; /* the representation of the double 3.1415 in the union */
/* eg. [111 18 -125 -64 -54 33 9 64] */
return 0 ;
}
Note: This code was tested on Visual C++ 2010.
It doesn't mean it will work that way (or at all) on your platform, but usually, you should get results similar to what happens above.
In the end, the garbage is just the hexadecimal data set in the memory your looking at, but seen as some type.
As most types have different memory representation of the data, looking at the data in any other type than the original type is bound to have garbage (or not-so-garbage) results.
Your printf could well behave like that, and thus, try to interpret a raw piece of memory as a double when it was initially set as an int.
P.S.: Note that as the int and the double have different size in bytes, the garbage gets even more complicated, but it is mostly what I described above.
But I want to print an int as a double!
Seriously?
Helios proposed a solution.
int main()
{
int x=10;
printf("%f",(double)(x));
return 0;
}
Let's look at the pseudo code to see what's being fed to the printf:
/* printf("...", [[10 0 0 0]]) ; */
printf("%i",x);
/* printf("...", [[10 0 0 0 ?? ?? ?? ??]]) ; */
printf("%f",x);
/* printf("...", [[0 0 0 0 0 0 36 64]]) ; */
printf("%f",(double)(x));
The casts offers a different memory layout, effectively changing the integer "10" data into a double "10.0" data.
Thus, when using "%i", it will expect something like [[?? ?? ?? ??]], and for the first printf, receive [[10 0 0 0]] and interpret it correctly as an integer.
When using "%f", it will expect something like [[?? ?? ?? ?? ?? ?? ?? ??]], and receive on the second printf something like [[10 0 0 0]], missing 4 bytes. So the 4 last bytes will be random data (probably the bytes "after" the [[10 0 0 0]], that is, something like [[10 0 0 0 ?? ?? ?? ??]]
In the last printf, the cast changed the type, and thus the memory representation into [[0 0 0 0 0 0 36 64]] and the printf will interpret it correctly as a double.
essentially it's garbage. Small integers look like unnormalized floating point numbers which shouldn't exist.
You could cast the int variable like this:
int i = 3;
printf("%f",(float)(i));