DEV Community

Sujith V S
Sujith V S

Posted on

Pointers in C programming.

Pointer in c allow us to work directly with the computer memory.

Memory Addresses

In c programming whenever we declare a variable a space will be allocated in the memory for the variable and C allows us to access the address of the variable. We use & with variable name to access the memory address.
Example:

int main() {
    int age = 25;
    printf("%p", &age);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

0x7ffcad58272c
Enter fullscreen mode Exit fullscreen mode

The format specifier %p(pointers) and & is used to get the memory address where 25 is located.

scanf("%d", &age);- with scanf we are instructing the compiler to store the input value at the memory address specified by this &age.

Pointer Variable

The pointer variable stores the memory addresses of the available value.
Example: int* ptr;

Assigning value(memory address) to a pointer variable

int main() {
    int age = 25;
    printf("%p", &age);

    int* ptr = &age; //assigned value.

    printf("\n%p", ptr);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Access value using pointer
Here we are trying to access the value of a variable using pointer variable.

int main() {
    int age = 25;

    int* ptr = &age; 

    printf("Address: %p\n", ptr);

    printf("Value: %d", *ptr); 

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

printf("Value: %d", *ptr);- it gives the value stored in a memory address.

Change value using pointer

int main() {
    int age = 25;

    int* ptr = &age; 

    *ptr = 31; 

    printf("%d", age);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In the above code, the initially assigned value is 25.
*ptr = 31; - it assigns a new value pointed by the ptr variable.
printf("%d", age); - now the value is changes to 31. because it points directly to the address and change the value to 31.


int* ptr = 32; (Invalid)
ptr is a pointer and it can only store memory address. And if we try to assign a value or number to it then it will become invalid.

*ptr = &number; (invalid)
*ptr stores the value and if we try to assign a memory address then it becomes invalid.

ptr = &number; (valid) - assigning address.

*ptr = number; (valid) - assigning value.

Top comments (0)