So, I'm trying to add malloc to the phone book application that I created, but since I'm a little new to C. I'm not sure what I'm doing is correct. I ran into a small problem, but I read the book of beginners, which I have, and it does not work, although in detail, as I would like, I canβt tell by finding Google if Iβm just completely wrong in the way I installed malloc , or if there is anything else that I missed.
Basically, I have 4 arrays in my structure, First_Name , Last_name , home , cell . Each of them has 2 functions, a function that receives information from the user and a function that prints and adds user information to the phone book. What I have now is a small snipit of source code that only adds the first name to the phonebook (so this is not all the code), and in every function that receives user input, I want to add the malloc function. Now I have only the first name and the first malloc setup, but the problem is that when I go to check the phone book to find out if the name was successfully entered, the program quits. If I select malloc, it will work successfully.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h> #define BUFFER 50 //Structure for contacts typedef struct friends_contact { char *First_Name; char *Last_Name; char *home; char *cell; } fr; void menu(fr * friends, int *counter, int user_entry, int i); void setFirst(fr *, int *, int i); char getFirst(fr *, int i); void add_contact(fr * friends, int *counter, int i); void print_contact(fr * friends, int *counter, int i); int main() { int user_entry = 0; fr *friends; int counter = 0; int i = 0; menu(friends, &counter, user_entry, i); getch(); return 0; } //Menu function void menu(fr * friends, int *counter, int user_entry, int i) { do { int result; printf("\nPhone Book Application\n"); printf ("1) Add friend\n2) Delete friend\n3) Show a friend\n4)Showphonebook\n5)Exit\n"); scanf("%d", &user_entry); if (user_entry == 1) { add_contact(friends, counter, i); } if (user_entry == 2) { } if (user_entry == 3) { } if (user_entry == 4) { print_contact(friends, counter, i); } } while (user_entry != 5); } void setFirst(fr * friends, int *counter, int i) { // THE MALLOC FUNCTION! friends = (fr *) malloc(BUFFER * sizeof(fr)); printf("Enter a first name \n"); scanf("%s", friends[*counter].First_Name); if (friends != NULL) { free(friends); } } char getFirst(fr * friends, int pos) { printf("%s ", friends[pos].First_Name); return *friends[pos].First_Name; } void add_contact(fr * friends, int *counter, int i) { setFirst(friends, counter, i); (*counter)++; } void print_contact(fr * friends, int *counter, int i) { for (i = 0; i < *counter; i++) if (strlen(friends[i].First_Name)) { getFirst(friends, i); } }
Looking to give a big green tick to someone who can help me.