Question:
Explain this c pointer program?
Nisha Mmm
2012-04-07 00:29:18 UTC
include
#include
int *func(int *p, int n);
main()
{
int arr[10]={1,2,3,4,5,6,7,8,9,10}, n, *ptr;
n=5;
ptr=func(arr,n);
printf("arr=%p, ptr=%p, *ptr=%d\n", arr,ptr,*ptr);
getch();
}
int *func(int *p, int n)
{
p=p+n;
return p;
}
output
arr=0023FF40, ptr=0023FF54, *ptr=6

Please explain each step..
I know pointer arithmatic.. i don't how this output has come
Three answers:
James Bond
2012-04-07 00:45:15 UTC
In C language, language supported array names themselves pointers to those arrays.

For example,

int arr[10]; Here, arr is a pointer.

char x[20]; Here x is character pointer. Because of this reason only while reading data into a string using scanf we dont use address operator.

scanf(%s", x);



However, these pointer can be critically called as constant pointers. That is, we can not apply increment or decrement operators on them unlike dynamic pointers. That is, when an array is declared some memory is allocated and its address is assigned the array names. We can not make it to change to some other memory later.



int *p;

p=(int*) malloc(100);

This is dynamic pointer on that we can do p++, p-- etc.



However,

int q[10];

Though q is a pointer, we can not do q++ or q--;



Thus in your printf statement arr value is printed 0023FF40 while p+n where n is 5 has returned as 0023FF54. It is acceptable, on your machine integer might be taking 4 bytes. Thus, 0023FF40+4*5=0023FF54. Hexadecimal addition. That is

0x0023FF40

0x00000014

----------------

0x0023FF54
Nick T
2012-04-07 07:52:05 UTC
because its NOT printing the address of the pointer but its contents (*ptr not ptr). and since it started as the address of element 0 ( 0023FF40 content = 1), when you add 5 to it you move to 0023FF54 (element 5) when you dereference it you get its contents which is 6.
2012-04-07 08:49:23 UTC
c pointer program is used to store the variable address.. it show the address..


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...