我正在研究一個簡單的「電話索引」項目。 我的項目是做出來的:結構,數組,指針如何通過指向這些結構的指針數組訪問結構的成員
if've:
索引來定義人的結構:
和三個函數來創建用戶,將它們添加到索引,顯示指數:
這裏是我的代碼:
// 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)
我已經嘗試了幾種解決方案,但它不工作。
在此先感謝。
你在'add_index返回一個指針到本地陣列()':'r'是本地所以'回報R等'使它超出範圍。使用它產生的指針是未定義的行爲。您還需要動態內存分配。順便說一下,您獲取用戶輸入的方法非常危險。不要使用'scanf()';總是更喜歡'fgets()'(它更容易避免緩衝區溢出錯誤)。 – 2015-02-06 15:15:21