CHAPTER -8

        Computer Science HSLC SEBA Board

        Pointer in C

        Bottom

        Exercise

        1. How is a pointer variable different from normal variable?

        A pointer variable is different from a normal variable in that it does not store a direct value but instead stores the memory address of another variable.

         

        2. Why dynamic memory allocation is an efficient memory management technique?

        Dynamic memory allocation is efficient because it allows programs to request and release memory as needed during runtime. It provides flexibility, reduces memory wastage, and efficiently handles variable-sized data structures. This flexibility improves program stability, resource utilization, and control over memory management, making it a valuable technique for efficient memory use.

         

        3. How many bytes are needed to store an int pointer variable? Is it same for character pointer variable. Write a program to explain your answer.

        The number of bytes required to store a pointer variable in C or C++ can vary depending on the system and compiler being used.

        To store an integer type pointer variable, we need 4 bytes of memory space. And to store a character type pointer we need 1 byte memory space.

        For example

        #include <stdio.h>

        int main()

        {

            char c ='A';

            char *chptr;

            chptr =&c;

            printf("Size of Char pointer is %d", sizeof(*chptr));

         

            printf("\n");

           

            int d =10;

            int *intptr;

            chptr =&d;

            printf("Size of Char pointer is %d", sizeof(*intptr));

         

            return 0;

        }

        When you run this program, it will print the size of both char and int pointers on your specific system and compiler.

         

        This program uses the sizeof operator to determine the size of the pointer variables and then prints the results. The sizeof operator returns the size in bytes of the operand, which, in this case, is the pointer variable.

         

        4.

        a)   int *ptr, x=9;

              ptr =  &x;

              printf("\n%d", (*ptr)++);

         

        b) int *ptr, x=9;

            ptr =  &x;

            printf("\n%d", (*ptr)++);

            printf("\n%d", *ptr);

         

        c) int *ptr, x=9;

            ptr =  &x;

            int y = ++(*ptr);

            printf("\n%d", y);

         

        d) char *ptr, x= 'A';

            ptr =  &x;

            char y = *ptr;

            printf("\n%c",y);

         

        e) char *ptr, x= 'A';

            ptr =  &x;

            char y = (*ptr)++;

            printf("\n%c",y);

         

        f) char *ptr, x= 'A';

            ptr =  &x;

            char y = ++(*ptr);

            printf("\n%c",y);

         

        g) char *ptr, x= 'A';

            ptr =  &x;

            char *y;

            y=ptr;

            printf("\n%c",++(*y));

         

         

        Output = 9

         

         

         

         

        Output = 9

                         10

         

         

        Output =  10

         

         

         

         

        Output = A

         

         

         

         

         

        Output = A

         

         

         

         

        Output = B

         

         

         

         

        Output = B

         

        5. Write a c program to dynamically allocate memory from an array to store 10 integers and display the first 5 of them.

        #include <stdio.h>

        int main()

        {

           int *ptr, n=10, i;

           ptr = (int*)malloc(n*sizeof(int));

           for(i=0; i<n; i++)

           {

               printf("Enter element %d\n", i);

               scanf("%d", (ptr+i));

           }

           printf("\nThe first 5 element of the array are:\n");

           for(i=0; i<5; i++)

           {

               printf("%d",*(ptr+i));

           }

            return 0;

        }

         

        6.  Write a C program to dynamically allocate memory for an array to store runs scored by Virat Kohli in the last ODI cricket matches. Write a function to find the maximum one.

        #include <stdio.h>

        int *score, n=10;

        int maxScore();

        int main()

        {

           int i, max;

           score =(int*)malloc(n*sizeof(int));

           printf("Enter the Score of Virat Kohli in the last 10 ODI\n");

           for(i=0; i<n; i++)

           {

               printf("Enter %d match Score: ", i+1);

               scanf("%d", (score+i));

           }

           max= maxScore();

           printf("Maximum Score: %d\n", max);

            return 0;

        }

        int maxScore()

        {

            int i, m = *score;

            for(i=0; i<n; i++)

            {

                if(*(score+i)>m)

                {

                    m = *(score+i);

                }

            }

            return m;

        }

         

        7. Write a c program and define a function takes the length of your name as an input parameter and then allocates memory dynamically to store your name. write another function to display the name.

         

        #include <stdio.h>

        int main()

        {

            displayAndFreeName();

            return 0;

        }

        void displayAndFreeName()

           {

            int length;

            printf("Enter the length of your name: ");

            scanf("%d", &length);

            char *name = (char *)malloc((length + 1) * sizeof(char));

            if (name == NULL) {

                printf("Memory allocation failed. Exiting...\n");

                exit(1);

            }

            printf("Enter your name: ");

            scanf(" %s", name);

            printf("Your name is: %s\n", name);

            free(name);

        }

         

         

         

        8. write a C program to store some integer variable in an array.  then write functions to the following.

        1. To calculate the number of even numbers in the array.

        2. To dynamically allocate memory to a new array to store only the even numbers.

        3. To copy the even numbers from the first array to the second one.

         

        #include <stdio.h>

         

        int* allocateEvenArray(int arr[], int size, int evenCount);

        int countEvenNumbers(int arr[], int size);

        void copyEvenNumbers(int src[], int srcSize, int dest[], int destSize);

         

        int main() {

            int numElements;

         

            // Input the number of elements in the array

            printf("Enter the number of elements: ");

            scanf("%d", &numElements);

         

            if (numElements <= 0) {

                printf("Invalid number of elements. Please enter a valid value.\n");

                return 1;

            }

         

            int myArray[numElements];

            printf("Enter %d integer values:\n", numElements);

            for (int i = 0; i < numElements; i++)

           {

                scanf("%d", &myArray[i]);

            }

            int evenCount = countEvenNumbers(myArray, numElements);

            printf("Number of even numbers: %d\n", evenCount);

            int* evenArray = allocateEvenArray(myArray, numElements, evenCount);

         

            int copyArray[evenCount];

            copyEvenNumbers(myArray, numElements, copyArray, evenCount);

         

            printf("Even numbers in the second array:\n");

            for (int i = 0; i < evenCount; i++) {

                printf("%d ", copyArray[i]);

            }

            printf("\n");

         

            // Free dynamically allocated memory

            free(evenArray);

            return 0;

        }

          int countEvenNumbers(int arr[], int size)

            {

            int count = 0;

            for (int i = 0; i < size; i++)

            {

                if (arr[i] % 2 == 0)

                {

                    count++;

                }

            }

            return count;

        }

        int* allocateEvenArray(int arr[], int size, int evenCount)

            {

            int* evenArray = (int*)malloc(evenCount * sizeof(int));

            if (evenArray == NULL)

                {

                printf("Memory allocation failed. Exiting...\n");

                exit(1);

            }

            int evenIndex = 0;

            for (int i = 0; i < size; i++)

                {

                if (arr[i] % 2 == 0)

                {

                    evenArray[evenIndex] = arr[i];

                    evenIndex++;

                }

            }

            return evenArray;

        }

        void copyEvenNumbers(int src[], int srcSize, int dest[], int destSize)

         {

            int evenIndex = 0;

            for (int i = 0; i < srcSize; i++)

                {

                if (src[i] % 2 == 0 && evenIndex < destSize)

                 {

                    dest[evenIndex] = src[i];

                    evenIndex++;

                }

            }

        }

         

        9. Write a C program to store some integer variable in an array.  then write functions to the following.

        1. To calculate the number of non-zero elements that are divisible by 3.

        2. To dynamically allocate memory to a new array to store only those numbers.

        3. To copy the Selected elements from the first array to the second one. 4. To calculate the summation of these elements.

         

        #include <stdio.h>

         

        int* allocateSelectedArray(int arr[], int size, int selectedCount);

        int calculateSum(int arr[], int size);

        void copySelectedElements(int src[], int srcSize, int dest[], int destSize);

        int countDivisibleBy3(int arr[], int size);

        int main()

        {

            int numElements;

            printf("Enter the number of elements: ");

            scanf("%d", &numElements);

         

            if (numElements <= 0) {

                printf("Invalid number of elements. Please enter a valid value.\n");

                return 1;

            }

         

            int myArray[numElements];

         

            // Input the elements into the array

            printf("Enter %d integer values:\n", numElements);

            for (int i = 0; i < numElements; i++)

            {

                scanf("%d", &myArray[i]);

            }

         

            // Calculate the number of non-zero elements divisible by 3

            int selectedCount = countDivisibleBy3(myArray, numElements);

            printf("Number of non-zero elements divisible by 3: %d\n", selectedCount);

         

            // Dynamically allocate memory for a new array to store selected numbers

            int* selectedArray = allocateSelectedArray(myArray, numElements, selectedCount);

         

            // Copy selected elements from the first array to the second one

            int copyArray[selectedCount];

            copySelectedElements(myArray, numElements, copyArray, selectedCount);

         

            // Display the selected numbers in the second array

            printf("Selected numbers in the second array:\n");

            for (int i = 0; i < selectedCount; i++)

            {

                printf("%d ", copyArray[i]);

            }

            printf("\n");

         

            // Calculate the summation of selected elements

            int sum = calculateSum(copyArray, selectedCount);

            printf("Sum of selected elements: %d\n", sum);

         

            // Free dynamically allocated memory

            free(selectedArray);

         

            return 0;

        }

         

        int countDivisibleBy3(int arr[], int size)

        {

            int count = 0;

            for (int i = 0; i < size; i++)

                {

                if (arr[i] != 0 && arr[i] % 3 == 0)

                {

                    count++;

                }

            }

            return count;

        }

        int* allocateSelectedArray(int arr[], int size, int selectedCount)

        {

            int* selectedArray = (int*)malloc(selectedCount * sizeof(int));

            if (selectedArray == NULL)

                {

                printf("Memory allocation failed. Exiting...\n");

                exit(1);

            }

         

            int selectedIndex = 0;

            for (int i = 0; i < size; i++)

                {

                if (arr[i] != 0 && arr[i] % 3 == 0)

                {

                    selectedArray[selectedIndex] = arr[i];

                    selectedIndex++;

                }

            }

         

            return selectedArray;

        }

        void copySelectedElements(int src[], int srcSize, int dest[], int destSize)

         {

            int selectedIndex = 0;

            for (int i = 0; i < srcSize; i++)

                {

                if (src[i] != 0 && src[i] % 3 == 0 && selectedIndex < destSize)

                {

                    dest[selectedIndex] = src[i];

                    selectedIndex++;

                }

            }

        }

         

        int calculateSum(int arr[], int size)

        {

            int sum = 0;

            for (int i = 0; i < size; i++)

            {

                sum += arr[i];

            }

            return sum;

        }

        Table of Content