int main(void)
{
int n1 = 2, n2 = 5;
int *p = &n1, *q = &n2;
*p = *(q++);
printf("%d,%d", *p, *q);
return 0;
}
output= 5,5
Why the value of *q is 5 it should have some garbage value?
int main(void)
{
int n1 = 2, n2 = 5;
int *p = &n1, *q = &n2;
*p = *(++q);
printf("%d,%d", *p, *q);
return 0;
}
output= 2,2
And how is this happening?
Can anyone explain how precedence rule works in pointers?
*p = *(q++); is (more or less) equivalent to *p = *q; q++;, so p is fine. q++ will be evaluated, yielding the old value of q (i.e. the value pre-increment). What you're seeing there is the expected behavior.
You do have undefined behavior in the deference of q in the printf call though since q no longer points at memory you own at that point. A million different things could be causing that (e.g. last time the memory was allocated, maybe a 5 was there, the compiler is being too nice and trying to help you, etc), but you cannot and should not depend on this behavior. Doing so is dangerous, and this program would likely crash or output nonsense on many compilers/operating systems/hardware.
Why the value of *q is 5 it should have some garbage value?
It is due to the postfix incrementation in *(q++) which acts after the pointer dereference and the assignment to *p.
So, the current value of the address pointed by *q is assigned to *p, and then q is incremented to a "garbage value".
This strange result in printing 5,5 is undefined behaviour.
Related
Please help me understand how the value of q is initially 1 and later changes to 0.
Code:
#include <stdio.h>
int main()
{
int i=10;
int *p, *q;
p = &i;
printf("%u\n%u\n%u\n",p,q,*q);
*q++=*p++;
printf("%u\n%u\n%u\n%u",p,q,*p,*q);
return 0;
}
Output:
1527896876
1527897120
1
1527896880
1527897124
1527897124
0
int *p, *q;
p = &i;
printf("%u\n%u\n%u\n",p,q,*q);
int* is a wrong type for the format specifier %u. If you pass an argument of wrong type, then the behaviour of your program is undefined.
printf("%u\n%u\n%u\n",p,q,*q);
*q++=*p++;
Here, q has an indeterminate value. It doesn't point to any object. You indirect through the pointer to access an object that it points to. Which is a contradiction because it doesn't point to any object.
Indirecting through an indeterminate pointer results in undefined behaviour.
The behaviour of your program is undefined. That explains everything about the behaviour of the program.
I think what happens is that here
*q++=*p++;
the post-increment operator of q is executed after the assignment.
So, you basically set the value of q to p, and then you increment it.
Also, i don't think the increment operator of p does anything.
For a better understanding look at the following example
#include <stdio.h>
int main() {
int i = 10;
int *p;
int *q = new int[2];
q[0] = 9;
q[1] = 99;
p = &i;
printf("%u\n", *q);
*q++ = *p++;
printf("%u\n", *q);
printf("%u", *--q);
return 0;
}
9
99
10
Notice how, in the end q points to the next element, thanks to the post-increment operator.
Anyway, i have no idea what you are trying to do.
I have a segmentation fault with the following code and i really don't understand where the issue is...
int *p;
p[0]=1;
printf("%d\n",*p);
Thanks
p is uninitialized. p[0] (equivalent to *(p + 0), which is effectively *p) attempts to dereference it, which results in undefined behavior due to the indeterminate value in p.
To make the program well-defined you need to make it point to some allocated memory location:
int i;
int* p = &i;
p[0] = 1;
printf("%d\n", *p);
p is not initialized. You need to initialize it first before dereferencing, otherwise it will lead to undefined behavior.
int *p; // p is pointing to a random location in memory
int a;
p = &a; // p is pointing to the variable a
p[0] = 1;
int *p;
p is an uninitialized pointer and may point to any unauthorized memory and with the below statement you tend to write to some invalid memory -
p[0]=1;
You can allocate memory to do so -
int *p=malloc(sizeof(int));
if(p!=NULL){
p[0]=1;
printf("%d",p[0]);
}
free(p);
Can anyone explain the reason behind the second output? Also what is the difference between solving using int pointers and char pointers?
The second answer is coming out to be 0.
int main()
{
char arr[] = "geeksforgeeks";
char *ptr1 = arr;
char *ptr2 = ptr1 + 3;
printf ("ptr2 - ptr1 = %d\n", ptr2 - ptr1);
printf ("(int*)ptr2 - (int*) ptr1 = %d", (int*)ptr2 - (int*)ptr1);
getchar();
return 0;
}
Pointers of some type T point to objects of type T.
For example
int a[] = { 1, 2 };
int *p = a;
If you increase a pointer as for example
++p;
or
p = p + 1;
(take into account that these statements are equivalent) it will point to the next object of type T that follows the current object. So the value of the pointer will be increased by sizeof( T ) that to provide that the poiner indeed will point to the next element.
In the example above sizeof( int ) is (usually) equal to 4. So the value of the pointer will be increased by 4.
If you write
int a[] = { 1, 2 };
int *p = &a[0]; // the same as int *p = a;
int *q = &a[1];
then expression q - p will be equal 1 but the difference between the values stored in p and q will ve equal to sizeof( int ). p points to the first element of the array and q points to the second element of the array. It is so-called pointer arithmetic.
As for your result with subtracting int pointers then the behaviour is undefined. According to the C++ Standard
Unless both pointers point to elements of the same array object, or one
past the last element of the array object, the behavior is undefined
In your case int pointers do not point to elements of the same array. That they would point to the elements of the same array at least the difference of their values shall be equal to sizeof( int )
It's happen because char size is 1-byte, when int is 32Bit (4byte) variable
Edit keep pointer in the original array and ensure correct alignement to avoid undefined behaviour (see comment of Matt McNabb)
Because 3 < sizeof(int).
In pointer arithmetic, (int *) ptr2 - (int *) ptr1 gives real_addr_of_ptr2 - real_addr_of_ptr1) / sizeof(int) = 3 / 4. As it is integer division => 0 - this is not specified by C++ but is current implementation.
If you use : char *ptr2 = ptr1 + 8;, you will get : (int*)ptr2 - (int*) ptr1 = 2
As there are more than 8 characters in array, it can work, provided the original array is correctly aligned. To be coherent with the specs, it should have been declared :
union {
char arr[] = "geeksforgeeks";
int iarr[];
} uarr;
char *ptr1 = uarr.arr;
This may be simple but it confuses me.
int x;
int *p = NULL;
int *q = &x;
What happens when
q = p; // Address where q points to equals NULL .
&x = q; // I don't think this is possible .
*q = 7; // Value of memory where q is pointing to is 7?
*q = &x // That's just placing the address of x into memory where q points to right?
x = NULL;
q = p;
Yes. q now points to NULL, just like p.
&x = q;
Not legal. You cannot reassign the address of a variable.
*q = 7;
Yes, sets the memory of the address where q is pointing to 7. If q points to NULL then this will cause an error.
*q = &x;
Not legal, q points to an integer, so you cannot assign an address to it. This is legal, as there is an implicit cast from int* (&x) to int (*q), but not very safe. In C++, it is just a plain error. You are right in saying that it places the address of x (cast to an int) into the memory pointed to by q.
Adding to peters explanation
*q=&x
this becomes legal at *q=(int)&x .However on a 32 bit OS its good to write *q=(long)&x.
Note:Some Compilers wont give you an error on *q=&x
x = NULL;
x will become 0;
I have a program question, here is the code.
int main()
{
int *p,*q;
p=(int*)1000;
printf("%d ",p);
q=(int*)2000;
printf("%d",q);
printf("%d",(p-q));
return 0;
}
But answer coming as
1000
2000
-250
I am unable to understand what happen with p-q and why answer came as -250?
Correct but probably useless answer: p - q is equal to (1000 - 2000) / (sizeof int). For most C compiles, sizeof int is 4.
Potentially more useful answer: the effect of typecasts like (int*) 1000 is undefined. That code creates a pointer to an int at address 1000. That address is probably invalid. To create a pointer to an int with value 1000, write this:
int i = 1000;
int *p = &i;
Now p points to i, and *p, the value pointed to by p, is 1000.
Here is some correct code that may say what you meant:
int main() {
int i = 1000;
int j = 2000;
int *p = &i;
int *q = &j;
printf("i = %d *p = %d\n", i, *p);
printf("j = %d *q = %d\n", j, *q);
printf("*p - *q = %d\n", *p - *q);
}
When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them.
On your platform, an int is 4 bytes. There are -250 elements between address 2000 and address 1000.
Since p and q don't both point to the same array, the result is undefined. You could get any result, including the one you expect.
So much undefined behaviour in this program, the values printed are really quite immaterial.
p is a pointer variable, which can store only address of a int variable. But you are storing 1000 as an address, which is invalid. And then you are storing 2000 to the variable q.
Now you are doing pointer arithmatic p-q. Always pointer arithmatic will gives the output based on the size of the type of address. Which will work like (p - q)/sizeof(type).
Consider if p and q are char * variable, then p-q will gives you the output as -1000
In your case p and q are int * variable, then p-q will gives you the output as 250 if size of int is 4 bytes. Execute this on the compiler where size of int is 2 bytes, you will get a result as -500.