Reputation: 9
i am working on a simple ' Phone index ' project. my project is made out of : structures, arrays, pointers
if've :
a structure to define persons in the index :
and three functions to create users, add them to index, display the index :
Here is my code :
// This is my structure definition
typedef struct
{
char fname[30];
char lname[30];
char phnum[14];
} PERS;
// Function prototypes
PERS * add_person(void);
PERS ** add_index(int );
void show_index(PERS **, int );
// Function implementation
PERS * add_person(void)
{
PERS * p = (PERS *) calloc(1,sizeof(PERS)); // Dynamic allocation.
printf(" First name : ");
scanf("%s", p->fname);
printf(" Last name : ");
scanf("%s", p->lname);
printf(" Phone number : ");
scanf("%s", p->phnum);
return p; // return a pointer to the structure PERS
}
PERS ** add_index(int nbr)
{
int i = 0;
PERS * r[nbr]; // an array of pointers to PERS structures.
while(i < nbr)
{
r[i] = add_person(); // populate the array with pointers to PERS
i++;
printf("\n");
}
return r; // return the array
}
void show_index(PERS **rep, int nbr) // recieve the array
{
int i = 0;
while(i < nbr)
{ // display its content
printf("\n");
printf(" %s \n", rep[i]->fname);
printf(" %s \n", rep[i]->lname);
printf(" %s \n", rep[i]->phnum);
i++;
}
}
and of course the main program :
#include <stdio.h>
#include <stdlib.h>
#include "funcs.h"
int main()
{
PERS ** rep = add_index(3); // Create an index with three items
printf("\n\n");
show_index(rep,3);
printf("\n\n");
return 0;
}
This is my input :
First name : friend
Last name : name
Phone number : 4567234512
This is the error i get :
(null)
Segmentation fault (core dumped)
i've tried several solution but it's not working.
Thanks in advance.
Upvotes: 0
Views: 55
Reputation: 19874
You know what !! you can solve your issue by changing just a single line.
PERS **r= malloc(sizeof(PERS *) * nbr);
Use pointer to pointer and return this value from the function..
Upvotes: 1