SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Pointers And Dynamic Arrays
Exercise:
Self-test Exercises
Question:9 | ISBN:9780321531346 | Edition: 7

Question

Write a type definition for pointer variables that will be used to point to

dynamic arrays. The array elements are to be of type char. Call the type

CharArray.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <stdio.h>
#include <stdlib.h>

typedef char* CharArray;

int main() {
    int size = 5;
    CharArray arr = (CharArray)malloc(size * sizeof(char));

    if (arr == NULL) {
        printf("Failed to allocate memory for the array.\n");
        return 1;
    }

    // Assign values to the dynamic array
    arr[0] = 'H';
    arr[1] = 'e';
    arr[2] = 'l';
    arr[3] = 'l';
    arr[4] = 'o';

    // Access and print the elements of the array
    for (int i = 0; i < size; i++) {
        printf("%c ", arr[i]);
    }
    printf("\n");

    // Free the memory allocated for the array
    free(arr);

    return 0;
}

OUTPUT OF THE PROGRAM CODE:

H e l l o 

NOTE: 

In this example, we use the CharArray type to declare a pointer variable arr. We then dynamically allocate memory for an array of char elements using malloc. We can access and manipulate the elements of the array using the pointer arr. Finally, we free the allocated memory using free when we no longer need the array.

0 0

Discussions

Post the discussion to improve the above solution.