18.2k views
5 votes
Create a structure with variables for a character, a string, an integer, and a floating point number. [Note: Use Typedef way of creating the structure]. The structure string variable is a "char* stringp". In other words, the structure will have a pointer to a string. Do not initialize the structure at definition time.

User Maoritzio
by
5.9k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

//we are creataing a structure and naming it 'datatype' using typedef

typedef struct structure

{

int n;

char ch;

char *stringp;

float f;

} datatype;

void main()

{

//declaring 5 'datatype' type pointers using array

datatype *dataArray[5];

int i;

char str[500];

//dynamically allocating the structure pointers

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

dataArray[i] = (datatype *)malloc(sizeof(datatype));

//loop for data input

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

{

printf("\\Enter Data for structure %d:\\", i + 1);

printf("Enter an integer: ");

scanf("%d", &dataArray[i]->n);

printf("Enter a single character: ");

//we need fflush to clear the input stream in order to be able

// to take new values

fflush(stdin);

//notice the blankspace before %c, this makes scanf ignore the preceding '\\' character

scanf(" %c", &dataArray[i]->ch);

//we need fflush to clear the input stream in order to be able

// to take new values

fflush(stdin);

printf("Enter a string: ");

gets(str);

//dynamically allocating the size of stringp to fit the input string

//perfectly

dataArray[i]->stringp = (char *)malloc(sizeof(char) * (strlen(str) + 1));

strcpy(dataArray[i]->stringp, str);

printf("Enter a float: ");

scanf("%f", &dataArray[i]->f);

}

//output loop 1

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

{

printf("\\\\Structure %d", i + 1);

printf("\\Structure %d pointer: %p", i + 1, dataArray[i]);

printf("\\Character: %c", dataArray[i]->ch);

printf("\\Integer: %d", dataArray[i]->n);

printf("\\String: %s", dataArray[i]->stringp);

printf("\\Floating Point: %.1f", dataArray[i]->f);

}

//freeing the 5 pointers of memory

for(i = 0; i < 5; i++) free(dataArray[i]);

//output loop 2

printf("\\\\After free the malloc - the pointer are: ");

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

printf("\\Structure %d pointer: %p", i + 1, dataArray[i]);

}

User Aestrivex
by
6.0k points