C Programming - Const - Discussion

Discussion Forum : Const - Find Output of Program (Q.No. 3)
3.
What will be the output of the program?
#include<stdio.h>
int fun(int **ptr);

int main()
{
    int i=10;
    const int *ptr = &i;
    fun(&ptr);
    return 0;
}
int fun(int **ptr)
{
    int j = 223;
    int *temp = &j;
    printf("Before changing ptr = %5x\n", *ptr);
    const *ptr = temp;
    printf("After changing ptr = %5x\n", *ptr);
    return 0;
}
Address of i
Address of j
10
223
Error: cannot convert parameter 1 from 'const int **' to 'int **'
Garbage value
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
23 comments Page 2 of 3.

Prakash said:   9 years ago
Yes, @Ghengha's answer is right and the result will come as,

Before changing ptr = 29ff0c and after change ptr = 29fed8.

Rahul said:   10 years ago
How did this happen?

Ghengha said:   1 decade ago
#include<stdio.h>
int fun(const int **ptr);//*

int main()
{
int i=10;
const int *ptr = &i;
fun(&ptr);
return 0;
}

int fun(const int **ptr)//*

{
int j = 223;
int *temp = &j;
printf("Before changing ptr = %5x\n", *ptr);
*ptr = temp;
printf("After changing ptr = %5x\n", *ptr);
return 0;
}

Barcelona said:   1 decade ago
ptr is not a constant pointer but the value it points to is constant.
ptr is constant pointer, if it should declare like this
int * const ptr;
But it is declared like
const int *ptr;
ptr may points to some other location but the fact here is that it should contain value 10. however in question value changes to 223. that's why error is there.

Shru said:   1 decade ago
Ravi explanation is correct.

Bond said:   1 decade ago
The ptr is declared twice in the function. How come that is not an error?

Am12cs said:   1 decade ago
#include<stdio.h>
int fun(int **ptr);

int main()
{
int i=10;
const int *ptr = &i;{{Probably CONST INT*PTR IS ASSIGNED TO REFERENCE OF 'I' WHICH CNT BE ALTERED BUT PTR IN FUTURE CAN BE ASSIGNED SOMETHING ELSE WHICH WILL NOT GIVE AN ERROR.
const int *ptr = &i;
*PTR=12;//ERROR
ptr=10;//NO ERROR

const int *ptr = &i;
int fun(int **ptr)
{
int j = 223;
int *temp = &j;
printf("Before changing ptr = %5x\n", *ptr);
const *ptr = temp;// HERE IS THE ERROR
printf("After changing ptr = %5x\n", *ptr);
return 0;
}
}

Ranjit said:   1 decade ago
Ravi already said it.

Ptr is a const pointer. The argument of fun should be const too.

Indu said:   1 decade ago
Can Anyone Explain?

Ravi said:   1 decade ago
const pointer cannot be passed to non-const parameter.

In line :fun(&ptr);
ptr in non-const, but argument required is const **ptr .


Post your comments here:

Your comments will be displayed after verification.