I am unable to get this:
as we say int const*ptr; means ptr is a pointer to an const int.
In a example:
int x = 10;
int const*ptr = &x;
//Here *ptr = 12// will give error...
Then if we modify X = 12;// Why there's no error in this case....
Printable View
I am unable to get this:
as we say int const*ptr; means ptr is a pointer to an const int.
In a example:
int x = 10;
int const*ptr = &x;
//Here *ptr = 12// will give error...
Then if we modify X = 12;// Why there's no error in this case....
Because x is non-const.
But. if we write:
void main()
{
int x = 10;
const int*ptr = &x;
x = 12;
printf("%d", *ptr);
}// Here we are modifying value of X , doesn't it mean that we are modifying the value to whom the *ptr is pointing to, i mean if we write *ptr =12 it gives error , then ptr is pointing to x , and if we change x's value then why there's no error.
Yes, but not through the pointer, so that is fine.Quote:
Originally Posted by Tanushreeagr
The pointer is a pointer to const int. It turns out that the int itself is not const, but from the point of view of someone using the pointer, the int is const.
Thx , now i got it.... I am unable to What is the use of Function Pointers in C and C++language?.
Read The Function Pointer Tutorials.Quote:
Originally Posted by Tanushreeagr
int main()
{
int* ptr;
int n, i;
printf("How many numbers you want to enter: -");
scanf("%d", &n);
if((ptr = (int*)malloc(n * sizeof(int))) == 0)/// if we skip this statement??
{
return 0;
}
for(i = 0; i < n; i++)
{
printf("Enter number:- ");
scanf("%d", ptr + i);
}
printf("\n you have entered:- ");
for(i = 0; i < n; i++)
{
printf("%d ", ptr[i] );
}
free(ptr);
printf("%d", sizeof(ptr));
printf("\n%d", sizeof(ptr + i));
return 0;
}
In the above program as we know that normally the compiler doesn't enter if statement , then if we skip the if statement why there's is runtime error.
You better open a new thread for a new question!
Anyway, if you skip the if statement, you also skip the memory allocation for ptr. Thus ptr does not point to a valid address.
The conceptual difficulty here probably is that this if statement does the actual work that needs to be done (the allocation of the memory block) during the evaluation of its condtion. The actual body of the if instruction is only executed when that fails and is of secondary importance.