C Pointers
C Pointers
Address in C
If you have a variable var in your program, &var will give you its
address in the memory.
We have used address numerous times while using
the scanf() function.
scanf("%d", &var);
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var); // Notice the use of & before var
printf("address of var: %p", &var);
return 0;
}
Output
Note: You will probably get a different address when you run the
above code.
C Pointers
int* p;
Note: In the above example, pc is a pointer, not *pc . You cannot and
should not do something like *pc = &c ;
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
int* pc, c, d;
c = 5;
d = -15;
pc = &c; printf("%d", *pc); // Output: 5
pc = &d; printf("%d", *pc); // Ouptut: -15
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
2. c = 22;
4. c = 11;
5. *pc = 2;
#include <stdio.h>
int main()
{
int c = 5;
int *p = &c;
printf("%d", *p); // 5
return 0;
}
Why didn't we get an error when using int *p = &c; ?
It's because
int *p = &c;
is equivalent to
int* p = &c;
#include <stdio.h>
int main()
{
int x[4];
int i;
for(i = 0; i < 4; ++i)
{ printf("&x[%d] = %p\n", i, &x[i]); }
printf("Address of array x: %p", x);
return 0; }
Output
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
Similarly,
• ...
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0; }
When you run the program, the output will be:
#include <stdio.h>
int main()
{
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
ptr = &x[2];
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2
return 0;
}
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2