[英]how to access members of structures through an array of pointers to those structures
我正在做一個簡單的“電話索引”項目。 我的項目是由:結構,數組,指針
如果已經:
在索引中定義人員的結構:
和三個創建用戶的功能,將它們添加到索引,顯示索引:
這是我的代碼:
// 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++;
}
}
當然是主程序:
#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;
}
這是我的輸入:
First name : friend
Last name : name
Phone number : 4567234512
這是我得到的錯誤:
(null)
Segmentation fault (core dumped)
我已經嘗試了幾種解決方案,但是沒有用。
提前致謝。
你知道嗎 !! 您只需更改一行即可解決您的問題。
PERS **r= malloc(sizeof(PERS *) * nbr);
使用指針指向指針,然后從函數返回此值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.