Pointers and memory allocation
A pointer is a variable in the C programming language that stores the memory address of another variable. By accessing the memory location that the pointer is pointing to, pointers can be utilized to modify data in an indirect manner. Using pointers, dynamic memory allocation allocates memory as needed.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n integers
ptr = (int*) malloc(n * sizeof(int));
// Check if memory was allocated successfully
if (ptr == NULL) {
printf("Error: memory not allocated\n");
exit(0);
}
// Read n integers from the user and store them in the memory block
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", ptr+i);
sum += *(ptr+i);
}
printf("The elements are: ");
// Print the elements stored in the memory block
for (int i = 0; i < n; i++) {
printf("%d ", *(ptr+i));
}
printf("\n");
printf("The sum is: %d\n", sum);
// Free the dynamically allocated memory
free(ptr);
return 0;
}
Output:
Enter the number of elements: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
The elements are: 1 2 3 4 5
The sum is: 15
In this example, we use a pointer ptr to allocate memory for an array of n integers. We then read n integers from the user and store them in the memory block using pointer arithmetic (ptr+i). We also calculate the sum of the elements using pointer arithmetic. Finally, we print the elements and the sum, and free the dynamically allocated memory using the free function.