c - I'm trying to create a program with a loop that prompts the user to enter data in the array elements -
i'm trying create program loop prompts user enter data in array elements. , when user no longer can enter data, print screen data entered in last in, first out order.
and attempt...
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> struct name_age { char name[10]; int age; }; void printme(struct name_age info) { printf("name: %s\n", info.name); printf("age: %d\n", info.age); } int main() { int size = 0, = 0, j = 0; struct name_age * array_ptr = (struct name_age*)malloc((size + 1)* sizeof(struct name_age)); struct name_age myinfo = *array_ptr; printf("enter size of array: "); scanf("%d\n", size); (i = 0; < size; ++i) { printf("enter name: \n"); scanf("%s\n", myinfo.name); printf("enter age: \n"); scanf("%d\n", myinfo.age); } printme(myinfo); return 0; };
first, scanf("%d", &size)
replace scanf("%d\n", size)
, put &size
instead of size
argument(you need address), , put malloc
things after line of code, because need exact size
value before malloc
. same thing scanf
stuffs.
as want print out input names , ages in order, changed code this:
#include <stdio.h> #include <stdlib.h> struct name_age { char name[10]; int age; }; void printme(struct name_age *infolist, int size) { int i; (i = size-1; >= 0; --i) { printf("name: %s\n", infolist[i].name); printf("age: %d\n", infolist[i].age); printf("\n"); } } int main() { int size, i; printf("enter size of array: "); scanf("%d", &size); struct name_age * array_ptr = (struct name_age*)malloc(size* sizeof(struct name_age)); (i = 0; < size; ++i) { printf("enter name: \n"); scanf("%s", array_ptr[i].name); printf("enter age: \n"); scanf("%d", &array_ptr[i].age); } printme(array_ptr, size); return 0; }
try test , compare code, questions welcome.
Comments
Post a Comment