- Create pointers for a character, a string, an integer, a floating-point number, and an array of 10 integers.
- For each pointer (5 of them), dynamically allocate the memory and then assign values as follows. You can use malloc and or calloc.
- Use your name for the string (array of characters). (First Name: Manny)
- Use 100 for the integer.
- The character should be an ‘A’.
- The floating-point number should be 98.76
- The array of integers should be the numerals 0 through 9.
- Print out values for all five dynamically allocated variables.
- Free all dynamically allocated memory.
- The output should look something like this:
Character: A
Integer: 100
String: Caryl
Floating Point: 98.76
Array of Integers: 0 1 2 3 4 5 6 7 8 9
Solution:
#include < stdio.h>
#include < stdlib.h>
#include < string.h>
int main(int argc, char **argv)
{
/*
* Create pointers for a character, a string, an integer,
* a floating-point number and for an array of 10 integers
*/
char *chr_ptr;
char *str_ptr;
int *int_ptr;
float *float_ptr;
int *int_arr;
/**
* For each pointer (5 of them), dynamically allocate the memory
* and then assign values as follows
*/
chr_ptr = calloc(1, sizeof(char));
str_ptr = calloc(6, sizeof(char));
int_ptr = calloc(1, sizeof(int));
float_ptr = calloc(1, sizeof(float));
int_arr = calloc(10, sizeof(int));
/**
* Assign values
*/
*chr_ptr = 'A';
memset(str_ptr, 0, 6);
strcpy(str_ptr, "Manny");
*int_ptr = 100;
*float_ptr = 98.76;
for (int i = 0; i < 10; i++)
{
int_arr[i] = i;
}
/**
* Print out values for all five dynamically allocated variables
*/
printf("Character: %c\n", *chr_ptr);
printf("Interder: %d\n", *int_ptr);
printf("String: %s\n", str_ptr);
printf("Floating Point: %.2f\n", *float_ptr);
printf("Array of Intergers:");
for (int i = 0; i < 10; i++)
{
printf(" %d", int_arr[i]);
}
printf("\n");
/**
* Free all dynamically allocated memory
*/
free(chr_ptr);
free(str_ptr);
free(int_ptr);
free(float_ptr);
free(int_arr);
/**
* j o h n n y t u o t - g m a i l - c o m
*/
return 0;
}
Output: