In the following code I am trying to create an array of struct pointers which will hold 2 structures. I think my problem has something to do with the allocation of memory of the character. The code itself is self-explanatory but I can't seem to fix the issue when scanning for the second char variable.
#include <stdlib.h>
#include <string.h>
typedef struct Structure
{
char character ;
char* string ;
int integer ;
float floatingPoint ;
} Structure ;
void *insertData(struct Structure *x)
{
int i ;
for (i = 0 ; i < 2 ; i++)
{
printf("Enter a character: ") ;
scanf("%c", &x[i].character) ;
printf("Enter an integer: ") ;
scanf("%d", &x[i].integer) ;
printf("Enter a string: ") ;
scanf("%s", x[i].string) ;
printf("Enter a floating point: ") ;
scanf("%f", &x[i].floatingPoint) ;
}
}
void printData(struct Structure *x)
{
int i ;
for (i = 0 ; i < 2 ; i++)
{
printf("\n\n\t Pointer: \n") ;
printf("Character: %c\n", x[i].character) ;
printf("Integer: %d\n", x[i].integer) ;
printf("String: %s\n", x[i].string) ;
printf("Floating Point: %f\n", x[i].floatingPoint) ;
}
}
int main()
{
int i ;
struct Structure* pointers = (struct Structure*) malloc(2 * sizeof(struct Structure)) ;
for (i = 0 ; i < 2 ; i++)
{
//allocating mem for string
pointers[i].string = malloc(sizeof(char)) ;
}
insertData(pointers) ;
printData(pointers) ;
return 0;
}
Output:
Enter a character: A
Enter an integer: 69
Enter a string: Sheeesh
Enter a floating point: 6.9
Enter a character: Enter an integer: 111
Enter a string: string
Enter a floating point: 1.1
Character: A
Integer: 69
String: Sheeesh
Floating Point: 6.900000
Character:
Integer: 111
String: string
Floating Point: 1.10000